我正在编写 iPhone 应用程序,其中需要自定义 UITextField 类。对于我的文本字段,我需要缩进、文本之前的图像和最大字符数。为此,我创建了基于 UITextField 的自定义类。我所有的文本字段都将基于这个新类。我使用 Google 并搜索了 Stackoverflow,我发现在像我这样的情况下我必须使用self.delegate = self;
在此期间init
所以我不需要实现类似的方法textFieldShouldBeginEditing
or textFieldShouldEndEditing
在我的视图控制器类中。我所有的文本字段都将在故事板中创建,所以initWithCoder
。结果,在输入 1、2 或 3 个符号后,我收到无限循环和应用程序崩溃(我现在使用模拟器)。有趣的是,对于数字键盘或密码键盘来说,没有这样的问题。另外,如果我在 Mac 键盘上输入符号而不是在模拟器上输入符号,也没有问题。我尝试调试,但在崩溃期间它直接跳入循环并存在错误。
如何克服这个问题呢?
附:我问question https://stackoverflow.com/questions/25870007/i-receive-exc-bad-access-using-custom-uitextfield-how-to-trace-the-issue当我收到无限循环并且有评论说self.delegate = self;
可能会导致这样的循环,但我看到这个语句被广泛使用。可能是我没有正确执行此操作,但我无法弄清楚如何从 UITextField 中创建可重用的类。
EDIT:这是我的代码:
在 inti 上我初始化并设置边框颜色:
- (id)initWithCoder:(NSCoder *)aDecoder{
self = [super initWithCoder:aDecoder];
if (self) {
self.layer.borderColor=[[UIColor blackColor] CGColor];
self.delegate = self;
}
return self;
}
当我开始编辑时,我更改边框颜色并设置缩进(缩进集将在属性设置器中移动):
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
// Change border of text field that is editing to orange
textField.layer.masksToBounds=YES;
textField.layer.borderColor=[[UIColor orangeColor] CGColor];
textField.layer.borderWidth= 1.0f;
UIView *spacerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _leftIndent, 10)];
[self setLeftViewMode:UITextFieldViewModeAlways];
[self setLeftView:spacerView];
return YES;
}
完成编辑后,我返回背景颜色:
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
// Change border of text field that is edited to black
textField.layer.masksToBounds=YES;
textField.layer.borderColor=[[UIColor blackColor] CGColor];
textField.layer.borderWidth= 1.0f;
return YES;
}
在值更改时,我检查最大字符数:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
// Restrict number of symbols in text field to "maxSymbols"
NSUInteger oldLength = [textField.text length];
NSUInteger replacementLength = [string length];
NSUInteger rangeLength = range.length;
NSUInteger newLength = oldLength - rangeLength + replacementLength;
BOOL returnKey = [string rangeOfString: @"\n"].location != NSNotFound;
return newLength <= (int)_maxSymbols || returnKey;
}