概述
- UITextField輸入框的基本使用
- iOS中鍵盤的操作都由UITextField來操作(和Android略有不同)
重點:
- 輸入框輸輸入內容前後回調時機;
- 鍵盤的控制(鍵盤顯示類型;鍵盤的顯示和隱藏等);
- 輸入內容的獲取;
示例代碼
ViewController.h
#import <UIKit/UIKit.h>
//注意UITextFieldDelegate代理
@interface ViewController : UIViewController <UITextFieldDelegate>
{
//只能是單行的輸入框
UITextField *_textField;
}
@property (retain,nonatomic) UITextField* textField;
@end
ViewController.m
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize textField = _textField;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.textField = [[UITextField alloc] init];
//設置大小
self.textField.frame = CGRectMake(100, 100, 200, 40);
//設置字體大小(也可以設置樣式)
self.textField.font = [UIFont systemFontOfSize:14];
//邊框樣式
self.textField.borderStyle = UITextBorderStyleRoundedRect;
//軟鍵盤類型
self.textField.keyboardType = UIKeyboardTypeDefault;
//沒有輸入時候默認文字,類似Android中hint
self.textField.placeholder = @"please enter password";
//輸入框中內容
self.textField.text = @"哈哈哈哈";
//是否要將輸入內容展示爲*
self.textField.secureTextEntry = NO;
//軟鍵盤右下角按鈕的類型。
self.textField.returnKeyType = UIReturnKeySearch;
//將ViewController設置爲代理,類似Android中的setOnclickListener
self.textField.delegate = self;
[self.view addSubview:self.textField];
//彈出軟鍵盤
[self.textField becomeFirstResponder];
}
-(void) textFieldDidBeginEditing:(UITextField *)textField{
NSLog(@"輸入開始了");
}
-(void) textFieldDidEndEditing:(UITextField *)textField{
NSLog(@"輸入結束了,隱藏鍵盤之後的回調");
//獲取輸入之後的字符串
NSLog(@"result=%@",textField.text);
}
-(BOOL) textFieldShouldBeginEditing:(UITextField *)textField{
NSLog(@"是否允許輸入");
return YES;
}
-(BOOL) textFieldShouldEndEditing:(UITextField *)textField{
NSLog(@"是否可以結束輸入,隱藏鍵盤");
return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
NSLog(@"點擊了搜索");
//獲取輸入之後的字符串
NSLog(@"result=%@",textField.text);
return YES;
}
//點擊屏幕中空白處
-(void) touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
//不再作爲第一消息響應者(點擊空白處收起軟鍵盤)
[self.textField resignFirstResponder];
}
@end