经常使用的文本框主要有两种。TextFieldView 和 TextView
1、弹出键盘类型
self.textView.keyboardType = UIKeyboardTypeDefault;
self.textView.returnKeyType = UIReturnKeyDone;
上面是设置键盘为“完成”类型,TextFieldView需要在textFieldShouldReturn代理函数里写键盘回收代码
TextView可以在 (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text代理函数里来完成键盘回收
参数“text”是输入的字符,可以通过判断text是否等于“\n”来判断用户是否点击了完成按钮。
2、限制只能输入某种类型的数据(以数字为例)
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if(textField == self.txtSimcard)
{
if(range.length == 1 && string.length == 0)//允许键盘上的不可见字符,如退格键
{
return YES;
}
else
{
NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"0123456789- "];
NSRange range = [string rangeOfCharacterFromSet:set];
if(range.length == 0 || range.length == NSNotFound)
{
return NO;
}
else
{
return YES;
}
}
}
else
{
return YES;
}
}
3、获取当前输入光标的位置
CGPoint cursorPosition = [textView caretRectForPosition:textView.selectedTextRange.end].origin;
CGPoint point = [textView convertPoint:cursorPosition toView:self.window];
4、当选中键盘上的联想词时会触发
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField.text.length == self.maxLength && string.length != 0)
{
return NO;
}
[textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingDidEnd];
return YES;
}
- (void)textFieldDidChange:(UITextField *)textField//当选择键盘上的联想字时会触发
{
if (textField == self.txtName) {
if (textField.text.length > 10) {
textField.text = [textField.text substringToIndex:10];
}
}
}