1. 程式人生 > >ios 鍵盤右上角新增完成按鈕

ios 鍵盤右上角新增完成按鈕

在調出鍵盤後,我們通常希望在鍵盤的右上角新增一個完成的按鈕,也就是給鍵盤新增一個附屬的檢視。

我們知道,在uitextField或uitextView獲得焦點的時候,鍵盤彈出。要在鍵盤的右上角新增完成按鈕,其實就是通過設定它們的inputAccessoryView屬性實現的:

先看看現實方法:

UIToolbar *bar = [[UIToolbaralloc] initWithFrame:CGRectMake(0,0, SCREEN_WIDTH,44)];

UIButton *button = [[UIButtonalloc] initWithFrame:CGRectMake(SCREEN_WIDTH

- 60, 7,50, 30)];

    [button setTitle:@"完成"forState:UIControlStateNormal];

    [button setTitleColor:COLOR_ORANGE_LIGHTforState:UIControlStateNormal];

    [bar addSubview:button];

_textField.inputAccessoryView = bar;

效果差不多這樣子:



當然如果你覺得每次時候textField都需要新增這段程式碼太麻煩,有沒有一勞永逸的辦法:

答案是有,就是繼承uitextField,重寫它的drawRect:

- (void)drawRect:(CGRect)rect {

    [superdrawRect:rect];

UIToolbar *bar = [[UIToolbaralloc] initWithFrame:CGRectMake(0,0, SCREEN_WIDTH,44)];

UIButton *button = [[UIButtonalloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 60, 7,50, 30)];

    [button setTitle:@"完成"forState:UIControlStateNormal];

    [button

setTitleColor:[UIColorredColor] forState:UIControlStateNormal];

    button.layer.borderColor = [UIColorredColor].CGColor;

    button.layer.borderWidth =1;

    button.layer.cornerRadius =3;

    [bar addSubview:button];

self.inputAccessoryView = bar;

    [button addTarget:selfaction:@selector(print)forControlEvents:UIControlEventTouchUpInside];

}

- (void) print {

NSLog(@"button click");

}