为什么在将自己设置为委托时UITextField会锁定

时间:2013-03-14 11:00:52

标签: ios objective-c uitextfield

我有一个扩展UITextfield的类。我也有相同的类设置为它自己的委托,所以当选择文本字段时,我可以更改背景颜色。一旦我选择文本字段并键入几个字母,应用程序就会锁定并崩溃。

这是我的.m文件的样子

@implementation MyTextField

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.delegate = self;

    }
    return self;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    NSLog(@"run did begine editing");
    [self setBackgroundColor:[UIColor colorWithRed:0.204 green:0.239 blue:0.275 alpha:0.25]];
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    NSLog(@"run did end editing");
    [self setBackgroundColor:[UIColor clearColor]];
}

这是.h

@interface MyTextField : UITextField <UITextFieldDelegate>

@end

3 个答案:

答案 0 :(得分:1)

委托总是另一个UIViewController,因为事件由另一个定义了协议的类委托给它。

当您可以访问同一类中的所有变量和方法时,不需要在同一个类中使用委托方法。

您只需拨打[self someFunction]

当您继承UITextField时,您甚至不需要为UITextField委托定义属性。您只需要将其设置为不同的viewController。

定义协议的类只有声明,并且不符合协议。

委托将是符合协议的类。

答案 1 :(得分:1)

订阅UITextFieldTextDidBeginEditingNotificationUITextFieldTextDidEndEditingNotification NSNotification。在回调中,检查通知对象是否为self。然后对它执行一些操作。

答案 2 :(得分:0)

此问题中的讨论应指导您朝着正确的方向self.delegate = self; what's wrong in doing that?