首页 > 代码库 > uitextField限制字数方法和抖动效果
uitextField限制字数方法和抖动效果
这个方法也是在网上找的。具体如下:
.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,可以通过它来扩展属性;
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。