禁止輸入框輸入emoji表情和空格
1.首先遵循UITextFieldDelegate
UITextField *textField = [[UITextField alloc] initWithFrame:frame];
textField.delegate = self;
[self.view addSubview:textField];
2.使用鍵盤的代理方法對輸入進(jìn)行控制監(jiān)聽
-(BOOL)textField:(UITextField *)textField shouldChangeCharacterInRange:(NSRange)range replacementString:(NSString *)string{
if([[[textField textInputMode] primaryLanguage] isEqualToString:@"emoji"] || ![[textField textInputMode] primaryLanguage] ){
return NO; //這里是限制表情輸入的
}
NSString *temp = [[string componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] componentsJoinedByString:@""];//限制空格
if(![string isEqualToString:temp]){
return NO;
}else{
return YES;
}
return YES;
}
修改占位文字的顏色
1.通過attributedPlaceholder屬性修改顏色。
NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:
@"請輸入占位文字" attributes:@{NSForegroundColorAttributeName:[UIColor redColor],
NSFontAttributeName:textField.font }];
textField.attributedPlaceholder = attrString;
2.通過KVC修改顏色
[textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
3.通過重寫UITextField的drawPlaceholderInRect:方法修改placeholder顏色
自定義一個(gè)TextField繼承自UITextField ;重寫drawPlaceholderInRect:方法 ;在drawPlaceholderInRect方法中設(shè)置placeholder的屬性。
// 重寫此方法
-(void)drawPlaceholderInRect:(CGRect)rect {
// 計(jì)算占位文字的 Size
CGSize placeholderSize = [self.placeholder sizeWithAttributes:
@{NSFontAttributeName : self.font}];
[self.placeholder drawInRect:CGRectMake(0, (rect.size.height - placeholderSize.height)/2, rect.size.width, rect.size.height)
withAttributes:@{NSForegroundColorAttributeName : [UIColor blueColor],NSFontAttributeName : self.font}];
}
當(dāng)我們使用純代碼創(chuàng)建UITextField時(shí),用第二種方法(KVC)修改占位文字顏色是最便捷的 。
當(dāng)我們使用XIB或者Storyboard創(chuàng)建UITextField時(shí),通過自定義UITextField,修改占位文字顏色是最適合的。
我們也可以在第三種重寫方法中,通過結(jié)合第二種方法中的KVC修改屬性來實(shí)現(xiàn)。
OK,完成!