iOS中实现键盘右上角完成按钮

重写UITextField子类的drawRect方法

class UITextFieldX: UITextField {
    override func drawRect(rect: CGRect) {
        super.drawRect(rect)
         
        // 键盘完成按钮
        var toolBar = UIToolbar(frame: CGRectMake(0, 0, screenSize().width, 30))
        toolBar.barStyle = UIBarStyle.Default
         
        var btnFished = UIButton(frame: CGRectMake(0, 0, 50, 25))
        btnFished.setTitleColor(RGB(4, 170, 174), forState: UIControlState.Normal)
        btnFished.setTitleColor(UIColor.grayColor(), forState: UIControlState.Highlighted)
        btnFished.setTitle("完成", forState: UIControlState.Normal)
        btnFished.addTarget(self, action: "finishTapped:", forControlEvents: UIControlEvents.TouchUpInside)
        var item2 = UIBarButtonItem(customView: btnFished)
         
        var space = UIView(frame: CGRectMake(0, 0, screenSize().width - btnFished.frame.width - 30, 25))
        var item = UIBarButtonItem(customView: space)
         
        toolBar.setItems([item,item2], animated: true)
         
        self.inputAccessoryView = toolBar
    }
     
    func finishTapped(sender:UIButton){
        self.resignFirstResponder()
    }
 
}
 
func screenSize() -> CGSize{
    return UIScreen.mainScreen().bounds.size
}
 
func RGB (r:CGFloat, g:CGFloat, b:CGFloat) -> UIColor {
    return UIColor(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: 1)
}

效果如下

iOS中实现键盘右上角完成按钮_第1张图片
效果图

你可能感兴趣的:(iOS中实现键盘右上角完成按钮)