Why does UITextField lock up when setting itself to delegate

夙愿已清 提交于 2019-12-01 10:06:03

问题


I have a class that extends UITextfield. I also have the same class set to be it's own delegate so when the text field is selected I can change the background color. Once I selecte the text field and type a couple of letters the app locks up and crashes.

here is what my .m file looks like

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

here is the .h

@interface MyTextField : UITextField <UITextFieldDelegate>

@end

回答1:


The delegate is always another UIViewController as the events are delegated to it by another class where protocol is defined.

There's no need of delegate methods in the same class when you can access all the variables and methods in the same class.

you simply can call [self someFunction].

As you are inheriting the UITextField , you don't need to define even a property for the UITextField delegate.You just need to set it a different viewController.

Also the class defining the protocol just has the declaration and it does not conform to the protocol.

The delegate will be the class which conforms to the protocol.




回答2:


Subscribe to UITextFieldTextDidBeginEditingNotification or UITextFieldTextDidEndEditingNotification NSNotifications. In callbacks check if notification object is self. Then perform some action on it.




回答3:


The discussion in this question should guide you in the right direction self.delegate = self; what's wrong in doing that?



来源:https://stackoverflow.com/questions/15407377/why-does-uitextfield-lock-up-when-setting-itself-to-delegate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!