How to set a custom NSTextStorage to a UITextView object created from a storyboard?

Viewed 438

I want to set a custom NSTextStorage to a UITextView object created from a storyboard. If it's really needed I can consider subclassing of UITextView.

(I know if I created a UITextView object from the code I would be able to use a init(frame: CGRect, textContainer: NSTextContainer?) constructor.)

Swift is preferable.

2 Answers

This works for me:

final class SendTextViewController: BaseViewController {
    @IBOutlet private var textView: UITextView!
    private var textStorage = MentionTextStorage()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        textView.textStorage.removeLayoutManager(textView.layoutManager)
        textStorage.addLayoutManager(textView.layoutManager)
     }
}

I was able to accomplish this by adding a UITextView subview to a UIView wrapper subclass that is instantiated from the storyboard. You can then add a getter on the view controller that returns the box's textView instance, so that you can assign yourself as the delegate, access properties etc...

Something like

class ViewController: UIViewController, UITextViewDelegate {

    @IBOutlet private weak var textViewBox: TextViewBox! // connected in storyboard

    var textView: UITextView! {
        return textViewBox?.textView
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        textView?.delegate = self
    }
}
Related