Custom Clear Button

后端 未结 3 947
旧时难觅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

    Implementing a custom text field as suggested in the other answers is not a good idea. You should try to use extensions rather than inheritance if at all possible, because with inheritance you are much more likely to need to make major changes to your codebase in response to changes, whereas using extensions you are much more flexible to change.

    I strongly suggest that instead of implementing a custom text field, you extend the UITextField class like this:

    extension UITextField {
        func applyCustomClearButton() {
            clearButtonMode = .Never
            rightViewMode   = .WhileEditing
    
            let clearButton = UIButton(frame: CGRectMake(0, 0, 16, 16))
            clearButton.setImage(UIImage(name: "iCFieldClear")!, forState: .Normal)
            clearButton.addTarget(self, action: "clearClicked:", forControlEvents: .TouchUpInside)
    
            rightView = clearButton
        }
    
        func clearClicked(sender:UIButton) {
            text = ""
        }
    }
    

    Then to use it you just do this:

    yourTextField.applyCustomClearButton()
    

提交回复
热议问题