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

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

问题描述

假设我在 UIView 中添加了 UITextView ,我希望它每次更改其背景颜色内容改变。我可以通过成为 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?

EDIT
看来我可以使用 self.delegate = self ,但是这意味着UIViewController使用 ColorSwitchingTextView 也不能订阅通知。一旦我在视图控制器中使用 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天全站免登陆