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

Categories

0 votes
623 views
in Technique[技术] by (71.8m points)

objective c - UITextView subclass as delegate of itself

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

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

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...