Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Let's say I add a UITextView to my UIView, and I want it to change its background color each time the contents change. I can do this by becoming the delegate of the UITextView and implementing textViewDidChange.

If I am using this behavior frequently though, it makes sense to create a UITextView subclass, which I will call ColorSwitchingTextView. It should include the color-switching behavior by default, so that any UIView can simply add it instead of a standard UITextView if it wants that behavior.

How do I detect changes in the content from within my ColorSwitchingTextView class? I don't think I can do something like self.delegate = self.

In summary, how can a UITextView subclass know when its contents change?

EDIT It seems I can use self.delegate = self, but this means that the UIViewController that uses the ColorSwitchingTextView can not also subscribe to the notifications. Once I use switchingTextView.delegate = self in the view controller, the subclass behavior no longer works. Any workarounds? I'm trying to get a custom UITextView that otherwise works like a regular UITextView.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
618 views
Welcome To Ask or Share your Answers For Others

1 Answer

In your subclass, listen for the UITextViewTextDidChangeNotification notification and update the background color when you receive the notification, like this:

/* 
 * When you initialize your class (in `initWithFrame:` and `initWithCoder:`), 
 * listen for the notification:
 */
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(myTextDidChange)
                                             name:UITextViewTextDidChangeNotification
                                           object:self];

...

// Implement the method which is called when our text changes:
- (void)myTextDidChange 
{
    // Change the background color
}

- (void)dealloc
{
    // Stop listening when deallocating your class:
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...