Custom Clear Button

后端 未结 3 1040
旧时难觅i
旧时难觅i 2020-12-15 12:48

I want to create custom clear button on UITextField, that is to use rightView and put image there, the problem is attaching the original clear button event to that custom r

3条回答
  •  孤街浪徒
    2020-12-15 13:18

    You can add a custom button as right view of the UITextField like this

    class CustomTextField : UITextField
    {
        override init(frame: CGRect) {
            super.init(frame: frame)
    
            let clearButton = UIButton(frame: CGRect(origin: .zero, size: CGSize(width: 15, height: 15))
            clearButton.setImage(UIImage(named: "clear.png")!, forState: UIControlState.Normal)
    
            self.rightView = clearButton
            clearButton.addTarget(self, action: "clearClicked:", forControlEvents: .touchUpInside)
    
            self.clearButtonMode = .never
            self.rightViewMode = .always
        }
    
        func clearClicked(sender: UIButton)
        {
            self.text = ""
        }
    
        required init(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
        }
    }
    

提交回复
热议问题