为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即可

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 16,185评论 4 61
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 179,622评论 25 708
  • Thank the flame for its light, but do not forget the lamp...
    我是呜呜阅读 489评论 0 0
  • 其实这种皮蛋挺漂亮的,像琥珀一样,里面还有雪花一样的花纹,这样的蛋还是魔鬼之蛋么,应该取个好听的名字,琥珀蛋~哈哈
    栖月阅读 292评论 0 0
  • 本文参加#乡忆·乡思·乡情·乡恋#活动,本人承诺,文章内容为原创,且未在其他平台发表过。 家乡,是自己可以说千万句...
    12赵凤婕阅读 250评论 0 1

友情链接更多精彩内容