为UTTextField(UITextView)增加UIToolBar

记录下如何 为键盘上添加工具栏

如果在您的应用中 使用输入框比较少的话,你可以直接为单个输入框增加UIToolBar

但是如果使用 输入框 地方比较多的时候,我们可以重定义 UITextField(UITextView)来一劳永逸的解决。方法如下:(toolbar 的UI 可以根据实际要求进行自定义)
这里我们以UITextField 为例,简单实现下。

-(void) awakeFromNib
{
    [super awakeFromNib];
    [self commonSets];
}

-(instancetype) initWithFrame:(CGRect)frame
{
   self = [super initWithFrame:frame];
    if (self) {
        [self commonSets];
    }
    return self;
}
-(void) commonSets
{
    self.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.layer.borderColor = UIColor.lightGrayColor.CGColor;
    UIView * leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, self.frame.size.height)];
    self.leftView = leftView;
    self.leftViewMode = UITextFieldViewModeAlways;
}

-(void) drawRect:(CGRect)rect
{
    [super drawRect:rect];

    UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, kSCREENSIZE.width, 44)];
    toolbar.tintColor = [UIColor blackColor];

    UIBarButtonItem * leftItem = [[UIBarButtonItem alloc] initWithTitle:nil style:UIBarButtonItemStylePlain target:self action:nil];

    UIBarButtonItem * leftFlexItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];

    UIBarButtonItem * centerItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"请输入信息", nil) style:UIBarButtonItemStylePlain target:self action:nil];
    [centerItem setTitleTextAttributes:@{NSForegroundColorAttributeName:UIColor.grayColor} forState:UIControlStateNormal];

    UIBarButtonItem * rightFlexItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];

    UIBarButtonItem * doneItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"button_write_toolbar_keyboard_down"] style:UIBarButtonItemStylePlain target:self action:@selector(textFieldDone)];
    toolbar.items = @[leftItem , leftFlexItem , centerItem ,rightFlexItem , doneItem];

    [self setInputAccessoryView:toolbar];
    [self setAutocorrectionType:UITextAutocorrectionTypeNo];
    [self setAutocapitalizationType:UITextAutocapitalizationTypeNone];

}

-(void) textFieldDone
{
    [self resignFirstResponder];
}

原理相似,在做文本编辑类的应用时,可以将UIBarButtonItem 替换成 其他icon即可

你可能感兴趣的:(为UTTextField(UITextView)增加UIToolBar)