iOS InputView 和 InutAccessoryView

一、InputAccessoryView

1、UITextFieldUITextView有一個InutAccessoryView的屬性,當你想在鍵盤上展示一個自定義的view時,你就可以設置該屬性。你設置的view就會自動和鍵盤keyboard一起顯示了,需要注意的是,你所自定義的view既不應該處在其他視圖層,也不應該成爲其他視圖的子視圖。其實也就是說,你所自定義的view只要賦給InutAccessoryView就可以了,不要再做其他多餘的操作。

2、我們在使用UITextFieldUITextView的時候,可以通過它們的InutAccessoryView屬性給輸入時呼出的鍵盤加一個附屬視圖,通常是UIToolBar,用於回收鍵盤。

3、但是當我們要操作的視圖不是UITextFieldUITextView的時候,InutAccessoryView就變成了readonly的。這時我們如果還想再加InutAccessoryView,按API中的說法,就需要新建一個該視圖的子類,並重新聲明InutAccessoryView屬性爲readwrite的。比如我們要實現點擊一個tableView的一行時,呼出一個UIPickerView,並且附加一個用於回收PickerViewtoolbar。因此我們自一個UITableViewCell類,並聲明InutAccessoryViewinputViewreadwrite的,並且重寫它們的get方法,這樣在某個tableviewcell變成第一響應者時,它就會自動呼出inputViewInutAccessoryView


二、InputView

1、inputView就是顯示鍵盤的view,如果重寫這個view則不再彈出鍵盤,而是彈出自己的view.如果想實現當某一控件變爲第一響應者時不彈出鍵盤而是彈出我們自定義的界面,那麼我們就可以通過修改這個inputView來實現,比如彈出一個日期拾取器。

2、inputView不會隨着鍵盤出現而出現,設置了inputView只會當UITextField或者UITextView變爲第一相應者時顯示出來,不會顯示鍵盤了。設置了InutAccessoryView,它會隨着鍵盤一起出現並且會顯示在鍵盤的頂端。InutAccessoryView默認爲nil.


三、示例代碼

#import "ViewController.h"

#define screenW [UIScreen mainScreen].bounds.size.width  //屏幕寬度
#define screenH [UIScreen mainScreen].bounds.size.height  //屏幕高度

@interface ViewController ()<UITextFieldDelegate>
@property (nonatomic, retain) UITextField * textField;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor grayColor];
    
    [self createToolBar];
}

- (void)createToolBar {
    // 定義一個toolBar
    UIToolbar * topView = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, screenW, 40)];
    
    // 設置style
    [topView setBarStyle:UIBarStyleBlack];
    
    // 定義完成按鈕
    UIBarButtonItem * doneButton = [[UIBarButtonItem alloc]initWithTitle:@"完成" style:UIBarButtonItemStyleDone target:self action:@selector(resignKeyboard)];
    
    // 在toolBar上加上這些按鈕
    NSArray * buttonsArray = @[doneButton];
    [topView setItems:buttonsArray];
    
    UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, screenW, 250)];
    label.text = @"InputView";
    label.textAlignment = NSTextAlignmentCenter;
    
    self.textField = [[UITextField alloc]initWithFrame:CGRectMake(50, 100, screenW - 100, 40)];
    self.textField.delegate = self;
    self.textField.placeholder = @"我是UITextField";
    self.textField.borderStyle = UITextBorderStyleRoundedRect;
    self.textField.inputView = label;
    self.textField.inputAccessoryView = topView;
    
    [self.view addSubview:self.textField];
    
}

// 隱藏鍵盤
-(void)resignKeyboard {
    [self.textField resignFirstResponder];
}

@end

結果:
                 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章