UITextField的用法

来源:互联网 发布:办公软件有问题 编辑:程序博客网 时间:2024/05/17 02:57

生成一个iOS->Application->Empty Application

在xxxDelegate.h头文件中添加UITextField的代理,以便此类能处理UITextField的事件

#import <UIKit/UIKit.h>@interface com_swordAppDelegate : UIResponder <UIApplicationDelegate,UITextFieldDelegate>@property (strong, nonatomic) UIWindow *window;@end

在对应的.m文件中,生成我们的UITextField

    UITextField *pwdText;    pwdText = [[UITextField alloc] init];    pwdText.frame = CGRectMake(80, 80, 200, 30);    pwdText.borderStyle = UITextBorderStyleRoundedRect;    pwdText.placeholder = @"输入密码";    pwdText.backgroundColor = [UIColor whiteColor];    pwdText.tag = 2;    pwdText.secureTextEntry = YES;    pwdText.keyboardType = UIKeyboardTypeNamePhonePad;    pwdText.keyboardAppearance = UIKeyboardAppearanceAlert;    pwdText.clearButtonMode = UITextFieldViewModeWhileEditing;    pwdText.delegate = self;    [self.window addSubview:pwdText];


borderStyle属性,定义样式,这里设置成圆角样式

placeholder为占位提示字符,就像我们注册帐号的时候,填帐号输入框里面有默认的文字提示

tag设置的标识号,方便判断是那个UITextField

secureTextEntry表示是否是密文,一般就是用来实现密码输入框

keyboardType键盘风格,有八种:

typedef enum {UIKeyboardTypeDefault, // 默认键盘:支持所有字符UIKeyboardTypeASCIICapable, // 支持ASCII的默认键盘UIKeyboardTypeNumbersAndPunctuation, // 标准电话键盘,支持+*#等符号UIKeyboardTypeURL, // URL键盘,有.com按钮;只支持URL字符UIKeyboardTypeNumberPad, //数字键盘UIKeyboardTypePhonePad, // 电话键盘UIKeyboardTypeNamePhonePad, // 电话键盘,也支持输入人名字UIKeyboardTypeEmailAddress, // 用于输入电子邮件地址的键盘} UIKeyboardType;

keyboardAppearance设置键盘的外观,有以下属性

typedef enum {UIKeyboardAppearanceDefault, // 默认外观:浅灰色UIKeyboardAppearanceAlert, //深灰/石墨色} UIKeyboardAppearance;
clearButtonMode,在UITextField末尾有个叉,和Safari输入网址的时候,地址栏末尾的叉一样,用来清除输入

然后把UITextField的代理和当前控制器绑定,记得用addSubview添加到视图中,不然是看不到的.

这样就可以实现UITextField的以下委托方法

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField;//准备开始进入编辑- (void)textFieldDidBeginEditing:(UITextField *)textField;//开始编辑- (BOOL)textFieldShouldEndEditing:(UITextField *)textField; //准备结束编辑- (void)textFieldDidEndEditing:(UITextField *)textField;//结束编辑- (BOOL)textFieldShouldClear:(UITextField *)textField;//准备清除输入内容- (BOOL)textFieldShouldReturn:(UITextField *)textField;//准备返回,回车或者点击了键盘上的return按钮

因此,我们可以利用最后一个方法textFieldShouldReturn让键盘收起来

-(BOOL)textFieldShouldReturn:(UITextField *)textField{    [textField resignFirstResponder];    NSLog(@"%@",pwdText.text);//设置了委托以后,我们就可以直接用点方法,获取text属性,便是TextField输入的内容    return YES;}



原创粉丝点击