swift:为键盘添加自定义工具栏

有时候需要为键盘添加一些自定义的按键,如“上一步”,“下一眇”,“完成” 按钮等。

首先自定义一个toolbar

func addToolbar() -> UIToolbar {
    var toolbar: UIToolbar = UIToolbar();
    toolbar.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: 35)
    toolbar.tintColor = UIColor.blue;
    toolbar.backgroundColor = UIColor.gray;
    var pre: UIBarButtonItem = UIBarButtonItem(title: "上一步", style: UIBarButtonItemStyle.plain, target: self, action: #selector(textFieldpre))
    var next: UIBarButtonItem = UIBarButtonItem(title: "下一步", style: UIBarButtonItemStyle.plain, target: self, action: #selector(textFieldnext))

    var space: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
    var bar: UIBarButtonItem = UIBarButtonItem(title: "完成", style: UIBarButtonItemStyle.plain, target: self, action: #selector(textFieldDone))
    toolbar.items = [pre, next, space, bar]
    return toolbar;

}

以及对应的响应方法

func textFieldDone() {
    hideKeyboard()
}

func textFieldpre() {
}


func textFieldnext() {
}

 

然后以UITextField初始化时加上

m_textField.inputAccessoryView = addToolbar()

这样就可以为为键盘加上自定义行为了。

 

 

发表评论