'how to archive UITextView and UITextField data binding

problem description: After currently changing the attribute of UItextView, when I change the content of UITextView by entering text in UITextField, the font style of UITextView becomes the initial state, but I have obviously changed the style

example:

import UIKit

class ViewController: UIViewController, UITextFieldDelegate, NSTextStorageDelegate {
    
let textview = UITextView()
let textField = UITextField()

override func viewDidLoad() {
    super.viewDidLoad()
    textview.backgroundColor = .gray
    textview.frame = CGRect(x: 100, y: 200, width: 200, height: 200)
    self.view.addSubview(textview)
    
    textview.text = "hello"
    textview.textStorage.addAttributes([NSAttributedString.Key.kern : 10],range: NSRange(location: 0, length: textview.text.count))
    
    textField.backgroundColor = .gray
    textField.frame = CGRect(x: 100, y: 600, width: 100, height: 40)
    textField.delegate = self
    self.view.addSubview(textField)
}
func textFieldDidChangeSelection(_ textField: UITextField) {
    textview.text = textField.text
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    textview.textStorage.addAttributes([NSAttributedString.Key.kern : 5],range: NSRange(location: 0, length: textview.text.count))
}

}



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source