常用方法
UITextFieldDelegate
self.textField = ({
UITextField * textField = [UITextField new];
textField.delegate = self;
textField.clearButtonMode = UITextFieldViewModeWhileEditing;
textField.keyboardType = UIKeyboardTypeDefault;
textField.placeholder = @"请输入";
textField.font = [UIFont systemFontOfSize:12];
textField.borderStyle = UITextBorderStyleNone;
[self.view addSubview: textField];
textField
});
//开始编辑时触发,文本字段将成为first responder
-(void)textFieldDidBeginEditing:(UITextField *)textField {
}
//是否允许文本字段结束编辑
-(BOOL)textFieldShouldEndEditing:(UITextField *)textField {
return NO;
}
//当用户使用自动更正功能,把输入的文字修改为推荐的文字时,就会调用这个方法。
-(BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
return YES;
}
//是否允许清除内容
-(BOOL)textFieldShouldClear:(UITextField *)textField {
return YES;
}
UITextField 光标的位置获取和设置
//#import "UITextField+ExtentRange.h"
import <UIKit/UIKit.h>
@interface UITextField (ExtentRange)
- (NSRange) selectedRange;
- (void) setSelectedRange:(NSRange) range;
@end
import "UITextField+ExtentRange.h"
@implementation UITextField (ExtentRange)
光标选择的范围 * * @return
获取光标选择的范围 */
- (NSRange)selectedRange{
//开始位置UITextPosition* beginning = self.beginningOfDocument;
//光标选择区域UITextRange* selectedRange = self.selectedTextRange;
//选择的开始位置UITextPosition* selectionStart = selectedRange.start;
//选择的结束位置UITextPosition* selectionEnd = selectedRange.end;
//选择的实际位置constNSInteger location = [self offsetFromPosition:beginning toPosition:selectionStart];
//选择的长度constNSInteger length = [self offsetFromPosition:selectionStart toPosition:selectionEnd];
returnNSMakeRange(location, length);
}
/** * 设置光标选择的范围* * @param range 光标选择的范围 */ - (void) setSelectedRange:(NSRange) range { UITextPosition* beginning = self.beginningOfDocument; UITextPosition* startPosition = [self positionFromPosition:beginning offset:range.location]; UITextPosition* endPosition = [self positionFromPosition:beginning offset:range.location + range.length]; UITextRange* selectionRange = [self textRangeFromPosition:startPosition toPosition:endPosition]; [self setSelectedTextRange:selectionRange]; }
限制输入字数:代码如下:
用的都是textView的delegate的方法:
-
(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
if(range.location > 100){
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
message:@"输入的自字符数不能超过300"
delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
[alert show];
[alert release];
return NO;
}else{
NSLog(@"%d",textView.text.length);
return YES;
}
}
2,显示剩余可输入字数,代码如下: -
(void)textViewDidChange:(UITextView *)textView{
int count;
count = shuzi - textView.text.length;
[_wordCount setText:[NSString stringWithFormat:@"%d", count]]; //_wordCount是一个显示剩余可输入数字的label
}
网友评论