ios – UITextFieldDelegate崩溃(exc_bad_access)

看起来我有UITextFieldDelegate的问题.

我刚刚创建了一个响应UITextFieldDelegate协议的视图控制器,并轻松地将字段添加到xib,然后设置委托字段……你知道.

但是当我尝试按下该字段时(开始编辑,程序崩溃).

当我尝试以编程方式创建字段时,会发生同样的事情.

这是调用堆栈:

这是完整的代码:

.H

#import <UIKit/UIKit.h>

@interface TopBar : UIViewController <UITextFieldDelegate>
{
    IBOutlet UITextField * field_top;
}

.M

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    NSLog(@"textFieldShouldBeginEditing");
    textField.backgroundColor = [UIColor colorWithRed:220.0f/255.0f green:220.0f/255.0f blue:220.0f/255.0f alpha:1.0f];
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    NSLog(@"textFieldDidBeginEditing");
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    NSLog(@"textFieldShouldEndEditing");
    textField.backgroundColor = [UIColor whiteColor];
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    NSLog(@"textFieldDidEndEditing");
}

代表由IB设定.

错误截图:

请帮忙.

最佳答案 确保你的.h中有这个

@interface TopBar : UIViewController <UITextFieldDelegate> {

}

@property (nonatomic, weak) IBOutlet UITextField *field_top;

并从@interface中删除

IBOutlet UITextField * field_top;

听起来你的field_top正在发布,而你正试图在以后访问它,这就是它崩溃的原因.

点赞