UITextField的使用
UITextField定义了一套代理,用来监听输入的内容
//设置默认提示文本
self.loginTextField.placeholder = @"手机号/QQ号/邮箱";
//设置textfield 的边框类型boardstyled
self.loginTextField.borderStyle = UITextBorderStyleRoundedRect;
[self.view addSubview:self.loginTextField];
//更改键盘下方的return的类型
self.loginTextField.returnKeyType = UIReturnKeyGoogle;
//设置键盘的类型
self.loginTextField.keyboardType = UIKeyboardTypeURL;
//设置delegate = self(当textfield的状态变了,当前这个类来接收回调方法)
self.loginTextField.delegate = self;
//设置左边的放大镜视图
UIImage *searchImage = [UIImage imageNamed:@"search"];
UIImageView *searchImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
searchImageView.image = searchImage;
self.loginTextField.leftView = searchImageView;
self.loginTextField.leftViewMode = UITextFieldViewModeAlways ;
//创建右边的下拉视图
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(0, 0, 15, 15);
[btn setImage:[UIImage imageNamed:@"down"] forState:UIControlStateNormal];
btn.tag = kChoiceButtonStatusDown;
[btn addTarget:self action:@selector(choiceUser:) forControlEvents:UIControlEventTouchUpInside];
UIView *rView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 30, 15)];
rView.backgroundColor = [UIColor clearColor];
[rView addSubview:btn];
self.loginTextField.rightView = rView;
self.loginTextField.rightViewMode = UITextFieldViewModeAlways;
-(void)choiceUser:(UIButton *)sender{
if (sender.tag == kChoiceButtonStatusDown) {
[sender setImage:[UIImage imageNamed:@"up"] forState:UIControlStateNormal];
sender.tag = kChoiceButtonStatusUp;
}else{
[sender setImage:[UIImage imageNamed:@"down"] forState:UIControlStateNormal];
sender.tag = kChoiceButtonStatusDown;
}
}
//当键盘的return键被按下了
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
//如何隐藏键盘
//当点击某个textfield,那么这个textfiled作为第一响应者,由于是一个textfield,需要用户输入内容,系统自动弹出键盘
//需要取消第一响应者,系统就会隐藏键盘
[textField resignFirstResponder];
return YES;
}
//当用户输入过程中,每按下一个字符,都会先来调用这个方法
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSLog(@"输入之前的字符%@",textField.text);
NSLog(@"输入了一个字符:%@",string);
NSLog(@"替换从%ld-%ld",range.location,range.length);
return YES;
}