让做个限制TextField输入长度的功能,本想着听简单的,直接去找对应的委托,在网上搜一下得到基本统一结论是使用下边的方法:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if ([string isEqualToString:@"\n"])
return YES;
//限制最大输入字符长度为9
NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
if (TRUE)
{
if ([toBeString length] > 9) {
textField.text = [toBeString substringToIndex:9];
return NO;
}
}
return YES;
}
没想到啊。。。。测试一直说没有限制输入长度,就自己试了几次,没有什么问题,一直到TMD发现了这个玩意:
这种情况,随便点没反应啊;
最后使用下边的方法成功了,大家可以看下:
[textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
-------------
- (void)textFieldDidChange:(UITextField *)textField
{
if (TRUE) { //这里应该判断下是哪个TextField
if (textField.text.length > 9) {
textField.text = [textField.text substringToIndex:9];
}
}
}
其实在UIKit框架的UIControl.h文件里定义了很多控件时间的枚举,很好用的:
typedef NS_OPTIONS(NSUInteger, UIControlEvents) {
UIControlEventTouchDown = 1 << 0, // on all touch downs
UIControlEventTouchDownRepeat = 1 << 1, // on multiple touchdowns (tap count > 1)
UIControlEventTouchDragInside = 1 << 2,
UIControlEventTouchDragOutside = 1 << 3,
UIControlEventTouchDragEnter = 1 << 4,
UIControlEventTouchDragExit = 1 << 5,
UIControlEventTouchUpInside = 1 << 6,
UIControlEventTouchUpOutside = 1 << 7,
UIControlEventTouchCancel = 1 << 8,
UIControlEventValueChanged = 1 << 12, // sliders, etc.
UIControlEventEditingDidBegin = 1 << 16, // UITextField
UIControlEventEditingChanged = 1 << 17,
UIControlEventEditingDidEnd = 1 << 18,
UIControlEventEditingDidEndOnExit = 1 << 19, // 'return key' ending editing
UIControlEventAllTouchEvents = 0x00000FFF, // for touch events
UIControlEventAllEditingEvents = 0x000F0000, // for UITextField
UIControlEventApplicationReserved = 0x0F000000, // range available for application use
UIControlEventSystemReserved = 0xF0000000, // range reserved for internal framework use
UIControlEventAllEvents = 0xFFFFFFFF
};