talshahar
talshahar

Reputation: 608

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 ?

Upvotes: 0

Views: 143

Answers (2)

Starsky
Starsky

Reputation: 2048

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
        }
    }
}

Upvotes: 0

flanker
flanker

Reputation: 4210

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

Upvotes: 1

Related Questions