iOS 键盘添加工具栏

有时候我们需要在键盘上面添加一些工具栏,比如上一项、下一项、完成等按钮,下面就以UITextField为例介绍一下如何添加这些工具栏。
将UITextField的inputAccessoryView属性设置成UIToolbar即可。
首先创建UIToolbar,代码如下

- (UIToolbar *)myToolbar
{
    if (_myToolbar == nil) {
        CGRect tempFrame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 44);
        _myToolbar = [[UIToolbar alloc] initWithFrame:tempFrame];
        
        UIImage *photoImg = [UIImage imageNamed:@"photo"];
        UIBarButtonItem *photoItem = [[UIBarButtonItem alloc] initWithImage:photoImg style:UIBarButtonItemStylePlain target:self action:@selector(photoItemClicked:)];
        
        UIImage *cameraImg = [UIImage imageNamed:@"camera"];
        UIBarButtonItem *cameraItem = [[UIBarButtonItem alloc] initWithImage:cameraImg style:UIBarButtonItemStylePlain target:self action:@selector(cameraItemClicked:)];
        
        UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
        
        UIImage *closeImg = [UIImage imageNamed:@"close"];
        UIBarButtonItem *closeItem = [[UIBarButtonItem alloc] initWithImage:closeImg style:UIBarButtonItemStylePlain target:self action:@selector(closeItemClicked:)];
        
        _myToolbar.items = @[photoItem, cameraItem, spaceItem, closeItem];
    }
    
    return _myToolbar;
}

对应的响应事件,只是简单地输出log,以及关闭第一响应者

#pragma mark - event response
- (void)photoItemClicked:(id)sender
{
    NSLog(@"调取系统相册");
}

- (void)cameraItemClicked:(id)sender
{
    NSLog(@"调取系统相机");
}

- (void)closeItemClicked:(id)sender
{
    NSLog(@"弹回键盘");
    [self.myTextField resignFirstResponder];
}

设置UITextField的inputAccessoryView属性

- (UITextField *)myTextField
{
    if (_myTextField == nil) {
        _myTextField = [[UITextField alloc] init];
        _myTextField.borderStyle = UITextBorderStyleRoundedRect;
        _myTextField.placeholder = @"欢迎关注";
        _myTextField.backgroundColor = [UIColor clearColor];
        _myTextField.inputAccessoryView = self.myToolbar;
    }
    
    return _myTextField;
}

这样就可以了,来看看效果吧

iOS 键盘添加工具栏_第1张图片
键盘工具栏截图.png

你可能感兴趣的:(iOS 键盘添加工具栏)