objective-c - UITextView 子类作为自身的委托(delegate)

标签 objective-c ios cocoa-touch uiview uitextview

假设我向我的 UIView 添加了一个 UITextView,并且我希望它在每次内容更改时更改其背景颜色。我可以通过成为 UITextView 的委托(delegate)并实现 textViewDidChange 来实现这一点。

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

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

总而言之,UITextView 子类如何知道其内容何时更改?

编辑 看来我可以使用 self.delegate = self,但这意味着使用 ColorSwitchingTextView 的 UIViewController 也不能订阅通知。一旦我在 View Controller 中使用 switchingTextView.delegate = self ,子类行为就不再有效。任何解决方法?我正在尝试获取一个自定义的 UITextView,它在其他方面的工作方式与常规 UITextView 相同。

最佳答案

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

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

关于objective-c - UITextView 子类作为自身的委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13336981/

相关文章:

objective-c - 如何在 If 语句中使用 NSMutableString 作为条件

iphone - 确定 UIView 的可用区域

objective-c - 无法在 iOS7 中自定义 UIProgressView?

objective-c - 在 MKMapView (iOS 6) 中禁用双击缩放

ios - 我可以在 UITextField 上设置插入点吗

objective-c - 从 View 调用类方法给出 : "Unrecognized selector sent to class"

ios - 在 KVO 中使用嵌套键路径

objective-c - 检查用户是否在连续的 UISlider 上完成滑动?

ios - Storyboard 中的组件重用

ios - 为什么异步函数后值没有更新?