UITextField 的基本用法
[code=objc]
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//self -> view -> textField -> self (内存泄露)
//默认没有边框
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(50, 100, 200, 30)];
//设置边框
textField.borderStyle = UITextBorderStyleRoundedRect;
//设置输入文本
// textField.text = @"请输入密码";
//设置字体
textField.font = [UIFont systemFontOfSize:22];
//文本颜色
textField.textColor = [UIColor redColor];
//提示字符
textField.placeholder = @"请输入密码";
//清空按钮
textField.clearButtonMode = UITextFieldViewModeWhileEditing;
//设置键盘样式
// textField.keyboardType = UIKeyboardTypeURL;
//设置代理监听输入框相关事件
textField.delegate = self; //控制器对象
//成为第一响应者(键盘会自动弹出)
// [textField becomeFirstResponder];
/**
*textField类的.m里面
if(_delegate response)
[_delegate textFieldShouldReturn:self]
*/
//设置return按钮的样式
textField.returnKeyType = UIReturnKeySend;
[self.view addSubview:textField];
}
#pragma mark -UITextFieldDelegate
//键盘将要弹出时,会调用此方法,如果返回yes则会弹出键盘
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
return YES;
}
//键盘弹出时,会调用此方法
- (void)textFieldDidBeginEditing:(UITextField *)textField {
NSLog(@"已经开始编辑");
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
NSLog(@"结束编辑,收回键盘时调用");
}
//return按钮被点击会调用此协议方法
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
NSLog(@"return按钮被点击");
//1. 键盘收回
[textField endEditing:YES];
//2. 键盘收回(失去第一响应者)
// [textField resignFirstResponder];
return YES;
}
//当编辑的时候,实时调用
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
// NSLog(@"%@",string);
if ([string isEqualToString:@"a"]) {
return NO;
}
return YES;
}
@end
[/code]