PB27
PB27

Reputation: 61

Setting inset on NSTextView

I have a textview setup in a scrollview (using code not 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 
    

I want to add an inset around the textview so the scrollview bar doesn't cover my text. What is the best approach?

Upvotes: 3

Views: 849

Answers (1)

PB27
PB27

Reputation: 61

In the end, I used two properties to achieve an inset.

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

1/ lineFragmentPadding

This creates horizontal padding but not vertical padding

2/ textContainerInset

This creates both kinds of padding, but if you use it for horizontal padding, you get a weird behaviour within the horizontal padding area. That is, the cursor is a text insertion cursor and when you click it doesn't select the text or move the cursor insertion point.

Hope that helps anyone with the same issue.

Upvotes: 3

Related Questions