/*
通知使用,可以通过接受系统通知来做一些事情
UITextField派生自UIControl,所以UIControl类中的通知系统在文本字段中也可以使用。除了UIControl类的标准事件,你还可以使用下列UITextField类特有的事件
UITextFieldTextDidBeginEditingNotification
UITextFieldTextDidChangeNotification
UITextFieldTextDidEndEditingNotification
当文本字段退出编辑模式时触发。通知的object属性存储了最终文本。
因为文本字段要使用键盘输入文字,所以下面这些事件发生时,也会发送动作通知
UIKeyboardWillShowNotification //键盘显示之前发送
UIKeyboardDidShowNotification //键盘显示之后发送
UIKeyboardWillHideNotification //键盘隐藏之前发送
UIKeyboardDidHideNotification //键盘隐藏之后发送
*/
委托方法
#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
//返回一个BOOL值,指定是否循序文本字段开始编辑
return YES;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
//开始编辑时触发,文本字段将成为first responder
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
//返回BOOL值,指定是否允许文本字段结束编辑,当编辑结束,文本字段会resign first responder
//要想在用户结束编辑时阻止文本字段消失,可以返回NO
//这对一些文本字段必须始终保持活跃状态的程序很有用,比如即时消息
return NO;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
//返回一个BOOL值,指明是否允许在按下回车键时结束编辑
return YES;
}
- (BOOL)textFieldShouldClear:(UITextField *)textField
{
/*
点击clear按钮时会调用此方法
返回一个BOOL值指明是否允许根据用户请求清除内容,可以设置在特定条件下才允许清除内容
*/
return YES;
}
- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
//当用户使用自动更正功能,把输入的文字修改为推荐的文字时,就会调用这个方法。
//这对于想要加入撤销选项的应用程序特别有用
//可以跟踪字段内所做的最后一次修改,也可以对所有编辑做日志记录,用作审计用途。
//要防止文字被改变可以返回NO
//这个方法的参数中有一个NSRange对象,指明了被改变文字的位置,建议修改的文本也在其中
return YES;
}
限制只能输入特定的字符
/*
限制只能输入特定的字符
*/
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *numbers = @"0123456789n";
// NSString *alphaNum = @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
NSCharacterSet *cs;
cs = [[NSCharacterSet characterSetWithCharactersInString:numbers]invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs]componentsJoinedByString:@""]; //按cs分离出数组,数组按@""分离出字符串
BOOL canChange = [string isEqualToString:filtered];
return canChange;
}
字数限制 :
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
// 键盘的Enter键
if ([text isEqualToString:@" "]) {
return YES;
}
int wordCount = [textView.text length] + text.length;
if(wordCount > _totalWord){ // _totalWorld为字数
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"字数限制"
message:[NSString stringWithFormat:@"不能超过%i字的上限哦!", _totalWord]
delegate:nil
cancelButtonTitle:@"确定"
otherButtonTitles:nil
];
[alert show];
return NO;
}else {
// self.wordnum.text = [NSString stringWithFormat:@"%d字", _totalWord - wordCount];
}
return YES;
}