歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> iOS UITextField 使用全解

iOS UITextField 使用全解

日期:2017/3/1 10:07:17   编辑:Linux編程

UITextField 座位用戶交互的一個必備使用的控件,其使用頻率較高。

定義一個UITextField 及其基本的屬性:

UITextField _telNum = [[UITextField alloc] init];
_telNum.clearsOnBeginEditing = NO;//在輸入時不清除原來輸入的文字
_telNum.delegate = self;//
[_telNum addTarget:self action:@selector(textFieldDoneEditing:) forControlEvents:UIControlEventEditingDidEndOnExit];//
_telNum.font = [UIFont boldSystemFontOfSize:14];//
_telNum.textColor = [UIColor blackColor];//
_telNum.backgroundColor = [UIColor clearColor];//
_telNum.borderStyle = UITextBorderStyleNone;
_telNum.clearButtonMode = UITextFieldViewModeWhileEditing;
_telNum.autocorrectionType = UITextAutocorrectionTypeNo;
_telNum.autocapitalizationType = UITextAutocapitalizationTypeNone;
_telNum.returnKeyType = UIReturnKeyDefault;
_telNum.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
_telNum.placeholder = @"默認的文本";
_telNum.keyboardType = UIKeyboardTypeNumberPad;//文本輸入時,按鍵彈出的按鍵為數字

下面為UITextField 的一些代理方法:

1.開始輸入文本時,一般需要判斷鍵盤是否遮擋住了UITextField 視圖,是的話需要調整整個視圖的位置。

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField {

CGRect textFrame = textField.frame;
float textY = textFrame.origin.y+textFrame.size.height;
float bottomY = self.view.frame.size.height-textY;
if(bottomY<216) //判斷當前的高度是否已經有216,如果超過了就不需要再移動主界面的View高度
{
float moveY = 216-bottomY;
prewMoveY = moveY;

NSTimeInterval animationDuration = 0.30f;
CGRect frame = self.view.frame;
frame.origin.y -=moveY;//view的Y軸上移
frame.size.height +=moveY; //View的高度增加
self.view.frame = frame;
[UIView beginAnimations:@"ResizeView" context:nil];
[UIView setAnimationDuration:animationDuration];
self.view.frame = frame;
[UIView commitAnimations];//設置調整界面的動畫效果
}
return YES;
}

2. 輸入文本結束時,調回輸入前的視圖布局

-(void ) textFieldDoneEditing:(id) sender{
if (sender == _telNum) {
_payButton.enabled = YES;

NSTimeInterval animationDuration = 0.30f;
CGRect frame = self.view.frame;
//還原界面
frame.origin.y +=prewMoveY;
frame.size. height -=prewMoveY;
self.view.frame = frame;
//self.view移回原位置
[UIView beginAnimations:@"ResizeView" context:nil];
[UIView setAnimationDuration:animationDuration];
self.view.frame = frame;
[UIView commitAnimations];
[sender resignFirstResponder];

}
}

3.決定文本輸入的字數,超過一定的范圍則彈出提示框:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (range.location>=11)
{
alertMessage(nil, @"超過了電話號碼的長度!");
return NO;
}
else
{
return YES;
}
}

Copyright © Linux教程網 All Rights Reserved