UITextView子类作为自己的委托

时间:2012-11-12 00:30:04

标签: objective-c ios cocoa-touch uiview uitextview

假设我向UITextView添加UIView,我希望每次内容更改时都更改其背景颜色。我可以成为UITextView的代表并实施textViewDidChange

如果我经常使用这种行为,那么创建UITextView子类是有意义的,我将称之为ColorSwitchingTextView。默认情况下,它应该包含颜色切换行为,以便任何UIView只需添加它而不是标准UITextView,如果它想要这种行为。

如何检测ColorSwitchingTextView课程内容的变化?我认为我不能做self.delegate = self之类的事情。

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

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

4 个答案:

答案 0 :(得分:23)

在您的子类中,收听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];
}

答案 1 :(得分:4)

最好从一开始就做好。

Apple和SOLID建议的是,不是UITextView,,而是UIView 。在您的自定义UIColorTextView中,您将成员UITextView作为子视图,您的UIColorTextView将是它的委托。此外,您的UIColorTextView将拥有它自己的委托,并将所需的委托回调从UITextView传递给它的委托。

我有一些这样的任务,不是使用UITextView,而是使用UIScrollView。

答案 2 :(得分:2)

在您的子类中,将self作为观察者添加到UITextViewTextDidChangeNotification

那就是说,我不同意正在进行的对话,即设置self作为代表是一个坏主意。对于这种特殊情况,当然,但这只是因为有更好的方法(UITextViewTextDidChangeNotification)。

答案 3 :(得分:1)

您可以使用NSNotificationCenter。

在子类中将委托设置为self(从未尝试过,但你说它有效),然后在视图控制器中你想要收到通知,

[[NSNotificationCenter defaultCenter] 
         addObserver:self 
         selector:@selector(textFieldDidBeginEditing:) 
         name:@"TextFieldDidNotification" object:nil];

并在子类中:

NSDictionary *userInfo = [NSDictionary dictionaryWithObject:self forKey:@"textField"];
[[NSNotificationCenter defaultCenter] postNotificationName:@"TextFieldDidBeginEditingNotification" object:self userInfo:userInfo]

现在你也可以传递字典中的任何其他信息。