UITextView 子类作为自身的委托 [英] UITextView subclass as delegate of itself

查看:18
本文介绍了UITextView 子类作为自身的委托的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我将 UITextView 添加到我的 UIView,并且我希望它在每次内容更改时更改其背景颜色.我可以通过成为 UITextView 的委托并实现 textViewDidChange 来做到这一点.

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.

如果我经常使用这种行为,创建一个 UITextView 子类是有意义的,我将其称为 ColorSwitchingTextView.默认情况下它应该包括颜色切换行为,以便任何 UIView 可以简单地添加它而不是标准的 UITextView 如果它想要这种行为.

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.

如何从我的 ColorSwitchingTextView 类中检测内容的变化?我不认为我可以做类似 self.delegate = self 的事情.

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.

总而言之,UITextView 子类如何知道其内容何时发生变化?

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

编辑看来我可以使用self.delegate = self,但这意味着使用ColorSwitchingTextView 的UIViewController 也不能订阅通知.一旦我在视图控制器中使用 switchingTextView.delegate = self,子类行为就不再起作用.任何解决方法?我正在尝试获得一个自定义的 UITextView,否则它就像一个常规的 UITextView.

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.

推荐答案

在您的子类中,监听 UITextViewTextDidChangeNotification 通知并在收到通知时更新背景颜色,如下所示:

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

这篇关于UITextView 子类作为自身的委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆