UITextField 雖然不是復雜的控件,但因為很多功能不熟悉的緣故,每次還是會浪費很多時間去實現想要的功能,下面對常用的方法進行一下匯總:
1、對輸入內容的監聽
通過監聽 UIControlEventEditingChanged 狀態,實現對輸入的內容的處理,常用于限制輸入位數、限制輸入內容等。
{
[self.passwordTextField addTarget:self action:@selector(textFieldDidChanged:) forControlEvents:UIControlEventEditingChanged];
[self.repeatTextField addTarget:self action:@selector(textFieldDidChanged:) forControlEvents:UIControlEventEditingChanged];
}
- (void)textFieldDidChanged:(UITextField *)textField
{
if (textField.text.length > 11) {
textField.text = [textField.text substringToIndex:11];
}
}
2、處理鍵盤彈出、收回事件。
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
[self keyboardAnimate:textField show:YES];
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
[self keyboardAnimate:textField show:NO];
}
- (void)keyboardAnimate:(UITextField *)textField show:(BOOL)willShow
{
CGFloat dist = self.backgroundView.frame.origin.y + [textField superview].frame.origin.y + textField.frame.origin.y + textField.frame.size.height - (self.backgroundView.frame.size.height - 216.0);
CGFloat offset = (willShow ? - dist : 0);
// 鍵盤彈出時,若dist為負,則不需要上移_backgroudView
if (willShow) {
if (dist < 0) {
offset = 0;
}
}
_backgroudViewTop.constant = offset;
[UIView animateWithDuration:0.25f animations:^{
[self.view layoutIfNeeded];
}];
}
注意:坐標原點在左上角、textFiled父視圖坐標。
思路
- 鍵盤彈出時,需要計算合適的視圖上移距離 offset,計算公式:
offset = textFiled 底部y - ( backgroundView.height - keyboard.height );
上面的例子中將 keyboard.height 直接設為216.0,可監聽鍵盤事件, 獲取當前鍵盤高度,更為準確。
- 修改背景視圖的frame,對整個視圖進行上移。
另,當父視圖或textFiled存在autoLayout關系時,需要更改對應的約束值,然后刷新autoLayout。
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *backgroudViewTop;
_backgroudViewTop.constant = offset;
[UIView animateWithDuration:0.25f animations:^{
[self.view layoutIfNeeded];
}];