UITextView和UITextField类似
UITextViewDelegate方法
#import "ViewController.h"@interface ViewController ()@end@implementation ViewController{
UITextField *textField1;
}- (void)viewDidLoad { [super viewDidLoad];
textField1 = [[UITextField alloc] init];
textField1.delegate = self;
//添加方法 [textField1 addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
textField1.frame = CGRectMake(10, 80, 200, 60);
textField1.backgroundColor = [UIColor grayColor];
[self.view addSubview:textField1];}
- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent *)event{
[textField1 resignFirstResponder];
// [self.view endEditing:YES];
}
static BOOL isWarned = YES;
- (void)textFieldDidChange:(UITextField *)tf
{
// 该判断用于联想输入 6个字符 3个汉字
[self limitCharater:tf limit:6];
}
//限制联想输入的字数
- (void)limitCharater:(UITextField *)tf limit:(int )count{
if ([self characterCount:tf] > count) {
while ([self characterCountWithString:tf.text] > count && tf.markedTextRange== nil) {
tf.text = [tf.text substringToIndex:tf.text.length - 1];
}
if (isWarned && tf.markedTextRange == nil) {
isWarned = NO;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
isWarned = YES;
});
}
}
}
/**
* 计算字符个数(一个汉字等于两个字符)
*/
- (NSInteger)characterCountWithString:(NSString *)string
{
NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
NSData* data = [string dataUsingEncoding:enc];
return data.length;
}
/**
* 计算字符个数(一个汉字等于两个字符)
*/
- (NSInteger)characterCount:(UITextField *)tf
{
NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
NSData* data = [tf.text dataUsingEncoding:enc];
return data.length;
}
@end