为了帮助初学者尽快的上手学习,特意抽一些时间 写一些简单的Demo 供大家学习
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// 文本输入框
UITextField *textField1 = [[UITextField alloc] init];
textField1.frame = CGRectMake(10, 440, 300, 30);
// 设置边框样式
textField1.borderStyle = UITextBorderStyleLine;
// 设置键盘风格
textField1.keyboardAppearance = UIKeyboardAppearanceDark;
// 设置键盘样式
//textField1.keyboardType = UIKeyboardTypeNumberPad;
// 设置密文输入
textField1.secureTextEntry = YES;
// 设置提示文字
textField1.placeholder = @"请输入密码";
// 设置清除按钮
textField1.clearButtonMode = UITextFieldViewModeAlways;
// 设置return健的样式
textField1.returnKeyType = UIReturnKeyGo;
textField1.minimumFontSize = 5.0f;
textField1.tag = 1001;
textField1.delegate = self;
// 设置弹出的视图
UIView *view = [[UIView alloc] init];
view.frame = CGRectMake(0, 0, 320, 150);
view.backgroundColor = [UIColor orangeColor];
textField1.inputView = view;
[self.view addSubview:textField1];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
btn.frame = CGRectMake(10, 100, 300, 30);
[btn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
btn.backgroundColor = [UIColor redColor];
// 订阅键盘升起和落下的系统通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide) name:UIKeyboardWillHideNotification object:nil];
}
- (void)keyboardWillShow
{
UITextField *textField = (UITextField *)[self.view viewWithTag:1001];
textField.frame = CGRectMake(10, 220, 300, 30);
}
- (void)keyboardWillHide
{
UITextField *textField = (UITextField *)[self.view viewWithTag:1001];
textField.frame = CGRectMake(10, 440, 300, 30);
}
- (void)btnClick
{
UITextField *textField = (UITextField *)[self.view viewWithTag:1001];
[textField resignFirstResponder];
}
// 是否可以进入编辑模式
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
return YES;
}
// 是否可以结束编辑模式
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
return YES;
}
// 清除按钮是否有效
- (BOOL)textFieldShouldClear:(UITextField *)textField
{
return YES;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
// 响应者
/*
1.点击return
2.点击空白地方
3.点击按钮
4.滑动
*/
// 取消第一响应者(收起键盘关闭光标)
[textField resignFirstResponder];
return YES;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
// 事件路由、事件分发
UITextField *textField = (UITextField *)[self.view viewWithTag:1001];
[textField resignFirstResponder];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end