我在 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/