I am trying to create a custom TextView. The problem I am getting is that when I try to conform to the NSLayoutManagerDelegate
the highlighting of the text inside it breaks, even though I have not implemented any of the delegate methods.
class TextView: UITextView, NSLayoutManagerDelegate {
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
layoutManager.delegate = self
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
layoutManager.delegate = self
}
}
And this is how I create the the TextView (everything is programmatic UI):
class ViewController: UIViewController {
let textView = TextView()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemBackground
view.addSubview(textView)
textView.isEditable = false
let loremIpsum = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehen."
let font = UIFont.preferredFont(forTextStyle: .body)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 15
textView.attributedText = NSMutableAttributedString(string: loremIpsum, attributes: [.font: font, .paragraphStyle: paragraphStyle])
textView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
textView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
textView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
textView.widthAnchor.constraint(equalToConstant: 300),
textView.heightAnchor.constraint(equalToConstant: 300)
])
}
}