swift - 在 NSTextView 上设置 inset

标签 swift nstextview nsscrollview

我在 ScrollView 中设置了 TextView (使用代码而不是 Storyboard)。

// 1. Text Storage
    let attrs = Style.body.attributes
    let attrString = NSAttributedString(string: text, attributes: attrs)
    textStorage = NSTextStorage(attributedString: attrString)
    
    // 2. Layout manager.
    layoutManager = LayoutManager()
    textStorage.addLayoutManager(layoutManager)
    layoutManager.delegate = self
    
    // 3. Layout Manager
    let containerSize = CGSize(width: self.bounds.width, height: .greatestFiniteMagnitude)
    let textContainer = NSTextContainer(size: containerSize)
    textContainer.widthTracksTextView = true
    layoutManager.addTextContainer(textContainer)
    
    // 4. TextView
    textView = NSTextView(frame: self.bounds, textContainer: textContainer)
    textView.delegate = self
    textView.typingAttributes = Style.body.attributes
    
    // 5. ScrollView
    scrollView = NSScrollView()
    scrollView.borderType = .noBorder
    scrollView.hasVerticalScroller = true
    scrollView.backgroundColor = .clear
    scrollView.drawsBackground = false
    scrollView.contentView.backgroundColor = .clear
    scrollView.translatesAutoresizingMaskIntoConstraints = false
    scrollView.borderType = .noBorder
    scrollView.hasVerticalScroller = true
    scrollView.documentView = textView
    
    // 6. Layout and sizing
    textView.minSize = NSSize(width: 0.0, height: scrollView.contentSize.height)
    textView.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
    textView.isVerticallyResizable   = true
    textView.isHorizontallyResizable = false
    textView.autoresizingMask = .width 
    

我想在 TextView 周围添加一个插图,这样 ScrollView 栏就不会覆盖我的文本。最好的方法是什么?

最佳答案

最后,我使用了两个属性来实现插图。

textView.textContainer?.lineFragmentPadding = 20
textView.textContainerInset = NSSize(width: 0, height: 20)

1/lineFragmentPadding

这会创建水平内边距,但不会创建垂直内边距

2/textContainerInset

这会创建两种填充,但如果将其用于水平填充,则会在水平填充区域内出现奇怪的行为。也就是说,光标是文本插入光标,当您单击它时,不会选择文本或移动光标插入点。

希望对遇到同样问题的人有所帮助。

关于swift - 在 NSTextView 上设置 inset,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67309241/

相关文章:

ios - 如何在iOS中显示来自网络的pdf

swift 包 --verbose generate-xcodeproj 给出错误 : reachedTimeLimit

macos - 如何在 TextView 中的某个索引处获取字符的行号和列号?

uitextview - 将多个 NSTextContainer 添加到 NSLayoutManager

swift - 以编程方式将 NSScrollView 滚动到右侧

cocoa - 魔术鼠标动量滚动不起作用

cocoa - NSTableCellView 内的 NSCollectionView 不会调整大小

Swift 如何将联系人保存为默认值

swift - 在 Swift 3 中搜索 Realm 关系

cocoa - NSLeftTextAlignment 字符串末尾带有空格