简体   繁体   中英

How can a UITextView listen on its own changes without delegate

I am making a custom UITextView subclass. The purpose is to support a placeholder, not natively supported for UITextView. The text view needs to listen on its own changes in order to show / hide the placeholder label. But I cannot use a delegate because the user class might reset the delegate to itself. How can I achieve this without any delegate methods?

It seems a little strange that you can't use a delegate , and it might be worth checking there's not a better architecture that would allow it, but if it's not feasible you could use notifications to alert you to activity in the textView .

TextViews issue textDidBeginEditingNotification , textDidChangeNotification , and textDidEndEditingNotification .

You could subscribe to these notifications, compare the text value against a stored version, and respond accordingly.

Details on this page: Apple docs for textView notifications

You can listen for the text value's changes, and act upon it. If there is at least one character, then we hide the placeholder, if there are 0 characters, we unhide the placeholder.

class CustomTextView: UITextView {

   override var text: String! {
        didSet (newValue) {
            let shouldHide = newValue.count > 0
            placeholder.isHidden = shouldHide
        }
    }
}

But I cannot use a delegate because the user class might reset the delegate to itself. How can I achieve this without any delegate methods?

Why would it do that? Have you placed YourTextView.delegate = self in multiple places? Have you already tried delegates?

This is the code for Delegates:

func textViewDidEndEditing(_ textView: UITextView) {

}

If you really don't want to use delegates you could use a timer that checks the textview very frequently and compares it to a previous value that you store. You could also check for keyboard actions and then checks the textview.

let timer = Timer(timeInterval: 0.0, repeats: true) { _ in 
 //put a conditional here that compares the textview text to the previously stored value
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM