为键盘增加收起按钮

2018-01-31  本文已影响15人  随缘吖

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

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

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

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

    UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 414, 44)];
    toolbar.tintColor = [UIColor blackColor];
    toolbar.backgroundColor = [UIColor lightGrayColor];
    UIBarButtonItem * spaceItem1 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];

    UIBarButtonItem * titleItem = [[UIBarButtonItem alloc] initWithTitle:@"请输入内容" style:UIBarButtonItemStylePlain target:self action:nil];
    [titleItem setTintColor:[UIColor lightGrayColor]];

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

    UIBarButtonItem *doneItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"完成",nil) style:UIBarButtonItemStylePlain target:self action:@selector(textFieldDone)];
    toolbar.items = @[spaceItem1 , titleItem , spaceItem2, doneItem];

    [self setInputAccessoryView:toolbar];

}

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

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

上一篇 下一篇

猜你喜欢

热点阅读