0

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 ?

talshahar
  • 528
  • 3
  • 12
  • https://stackoverflow.com/questions/3498158/intercept-objective-c-delegate-messages-within-a-subclass ? Using an procotol interceptor, like a man in the middle? – Larme Nov 06 '19 at 15:04

2 Answers2

1

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

flanker
  • 3,840
  • 1
  • 12
  • 20
0

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
        }
    }
}
Starsky
  • 1,829
  • 18
  • 25