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;

效果差不多这样子:

ios 键盘右上角添加完成按钮_第1张图片


当然如果你觉得每次时候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");

}


你可能感兴趣的:(ios)