这种方法还可以找到在线。
如下面的详细信息:
.h文件
#import <UIKit/UIKit.h>
@interface UITextField (LimitLength)
/**
* 使用时仅仅要调用此方法。加上一个长度(int),就能够实现了字数限制,汉字不能够
*
* @param length
*/
- (void)limitTextLength:(int)length;
/**
* uitextField 抖动效果
*/
- (void)shake;
@end
.m文件
#import "UITextField+LimitLength.h"
#import <objc/runtime.h>
@implementation UITextField (LimitLength)
static NSString *kLimitTextLengthKey = @"kLimitTextLengthKey";
- (void)limitTextLength:(int)length
{
objc_setAssociatedObject(self, (__bridge const void *)(kLimitTextLengthKey), [NSNumber numberWithInt:length], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
[self addTarget:self action:@selector(textFieldTextLengthLimit:) forControlEvents:UIControlEventEditingChanged];
}
- (void)textFieldTextLengthLimit:(id)sender
{
NSNumber *lengthNumber = objc_getAssociatedObject(self, (__bridge const void *)(kLimitTextLengthKey));
int length = [lengthNumber intValue];
if(self.text.length > length){
self.text = [self.text substringToIndex:length];
}
}
- (void)shake
{
CAKeyframeAnimation *keyAn = [CAKeyframeAnimation animationWithKeyPath:@"position"];
[keyAn setDuration:0.5f];
NSArray *array = [[NSArray alloc] initWithObjects:
[NSValue valueWithCGPoint:CGPointMake(self.center.x, self.center.y)],
[NSValue valueWithCGPoint:CGPointMake(self.center.x-5, self.center.y)],
[NSValue valueWithCGPoint:CGPointMake(self.center.x+5, self.center.y)],
[NSValue valueWithCGPoint:CGPointMake(self.center.x, self.center.y)],
[NSValue valueWithCGPoint:CGPointMake(self.center.x-5, self.center.y)],
[NSValue valueWithCGPoint:CGPointMake(self.center.x+5, self.center.y)],
[NSValue valueWithCGPoint:CGPointMake(self.center.x, self.center.y)],
[NSValue valueWithCGPoint:CGPointMake(self.center.x-5, self.center.y)],
[NSValue valueWithCGPoint:CGPointMake(self.center.x+5, self.center.y)],
[NSValue valueWithCGPoint:CGPointMake(self.center.x, self.center.y)],
nil];
[keyAn setValues:array];
NSArray *times = [[NSArray alloc] initWithObjects:
[NSNumber numberWithFloat:0.1f],
[NSNumber numberWithFloat:0.2f],
[NSNumber numberWithFloat:0.3f],
[NSNumber numberWithFloat:0.4f],
[NSNumber numberWithFloat:0.5f],
[NSNumber numberWithFloat:0.6f],
[NSNumber numberWithFloat:0.7f],
[NSNumber numberWithFloat:0.8f],
[NSNumber numberWithFloat:0.9f],
[NSNumber numberWithFloat:1.0f],
nil];
[keyAn setKeyTimes:times];
[self.layer addAnimation:keyAn forKey:@"TextAnim"];
}
@end
<span style="font-size: 14px; font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">在调用的地方例如以下:</span>
[m_userNamelimitTextLength:8];
这个类有个问题,就是不能对中文做限制,也会crash . 在使用时要注意,能够对textField设置键盘类型。
下个整理点:category与associative作为objective-c的扩展机制的两个特性,category即类型,能够通过它来扩展方法;associative,能够通过它来扩展属性;
整理地方:http://blog.csdn.net/quanqinyang/article/details/38017581
版权声明:本文博客原创文章,博客,未经同意,不得转载。