标签:
// UITextField的初始化
UITextField textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 320,30)];
//外框类型
[textField setBorderStyle:UITextBorderStyleRoundedRect];
//默认显示的字
textField.placeholder = @"默认显示的字";
//密码
textField.secureTextEntry = YES;
//是否纠错
text.autocorrectionType = UITextAutocorrectionTypeNo;
typedef enum {
UITextAutocorrectionTypeDefault, 默认
UITextAutocorrectionTypeNo, 不自动纠错
UITextAutocorrectionTypeYes, 自动纠错
} UITextAutocorrectionType;
//首字母是否大写
textField.autocapitalizationType = UITextAutocapitalizationTypeNone;
typedef enum {
UITextAutocapitalizationTypeNone, 不自动大写
UITextAutocapitalizationTypeWords, 单词首字母大写
UITextAutocapitalizationTypeSentences, 句子的首字母大写
UITextAutocapitalizationTypeAllCharacters, 所有字母都大写
} UITextAutocapitalizationType;
textField.returnKeyType = UIReturnKeyDone;
textField.clearButtonMode = UITextFieldViewModeWhileEditing; //编辑时会出现个修改X
//按return键返回
-(IBAction) textFieldDone:(id) sender
{
[textFieldName resignFirstResponder];
}
最右侧加图片是以下代码,
UIImageView *imgv=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"right.png"]];
text.rightView=imgv;
text.rightViewMode = UITextFieldViewModeAlways;
如果是在最左侧加图片就换成:
text.leftView=imgv;
text.leftViewMode = UITextFieldViewModeAlways;
UITextField 继承自 UIControl,此类中有一个属性contentVerticalAlignment
所以想让UITextField里面的text垂直居中可以这样写:
text.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
//删除文本框中选中的文本
[textView delete: nil];
//限制长度
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (range.location >= MAX_LENGTH)
return NO; // return NO to not change text
return YES;
}
if (textField.text.length >= 10 && range.length == 0)
return NO;
return YES;
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if ([textField.text length] > MAXLENGTH)
{
textField.text = [textField.text substringToIndex:MAXLENGTH-1];
return NO;
}
return YES;
}
// UITextFieldDelegate 协议
<UITextFieldDelegate>
//按键盘完成时取消焦点:
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder]; //取消焦点/隐藏键盘
return YES;
}
//设置焦点:
[UITextField becomeFirstResponder];
//绑定事件
textField.delegate = self;
ps:
有时可能会遇到 textFieldShouldReturn 函数写了,但是按键到 return 无法让键盘消失。这是因为你的文本框没有添加委托。添加委托的方法,右键文本框,把 outlets 下的+拉到 file‘s owner 上就可以了。 或者在加载事件中添加t xtLength.delegate=self;
标签:
原文地址:http://my.oschina.net/jack088/blog/502767