【发布时间】:2014-09-23 15:09:28
【问题描述】:
我知道互联网上有很多关于这个问题的信息,但我被困住了。我有一个应用程序,我需要在其中自定义我的UITextFields。例如,我需要在编辑开始时更改边框颜色,或者我需要限制我可以在不同的文本字段中设置多少个字符。我还需要几个文本字段中的图像,必须在左侧缩进。为此,我决定制作自定义 UITextField 类(子类 UITextField)。我从UITextField(实现<UITextFieldDelegate>)创建了新类。在那个类中,我使用self.delegate = self(这在互联网上被广泛使用,人们说它正在工作)所以我可以在我的自定义类中实现shouldChangeCharactersInRange 或textFieldShouldBeginEditing。我的问题是,在此配置中,我收到无限循环并重新启动应用程序(请参阅my question 关于此)。这来自self.delegate = self。我知道在某些情况下我可以使用observer,但在那种情况下,我如何在我的课堂上实现shouldChangeCharactersInRange?
如果我不以这种方式实现我的类并将我的文本字段委托给我的视图控制器。我必须在我的视图控制器类中实现所有这些方法,在我看来这是非常丑陋的解决方案。
所以我的问题是如何正确实现 UITextField 子类?
附:我想我做错了,但我不知道哪个是正确的。
编辑:
这是我的代码:
MyCustomTextField.h
@interface MyCustomTextField : UITextField
@property (nonatomic) int maxSymbols;
@property (nonatomic) int leftIndent;
@end
MyCustomTextField.m
@interface MyCustomTextField () <UITextFieldDelegate>
@end
@implementation MyCustomTextField
- (id)initWithCoder:(NSCoder *)aDecoder{
if (self = [super initWithCoder:aDecoder]) {
self.delegate = self;
self.clipsToBounds = YES;
[self setLeftViewMode:UITextFieldViewModeAlways];
UIImageView *imageView1 = [[UIImageView alloc]
initWithFrame:CGRectMake(0, 0, 37, 20)];
imageView1.image = [UIImage imageNamed:@"otp_back"];
self.leftView = imageView1;
}
return self;
}
- (CGRect) leftViewRectForBounds:(CGRect)bounds {
CGRect textRect = [super leftViewRectForBounds:bounds];
textRect.origin.x = 5;
return textRect;
}
还有这个检查最大长度的方法:
- (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;
}
当我转到文本字段并开始从模拟器的虚拟键盘键入时,我收到无限循环并以 BAD ACCESS 退出。这很奇怪,因为如果键盘是数字或密码类型,或者我从 Mac 键盘输入,我没有收到问题。
【问题讨论】:
-
你能展示一些实际的代码吗?很大程度上取决于你什么时候说什么。
标签: ios objective-c uitextfield