Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
299 views
in Technique[技术] by (71.8m points)

ios - Custom Clear Button

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 rightView.

In Objective-C i can do that this way:

SEL clearButtonSelector = NSSelectorFromString(@"clearButton");
// Reference clearButton getter
IMP clearButtonImplementation = [self methodForSelector:clearButtonSelector];
// Create function pointer that returns UIButton from implementation of method that contains clearButtonSelector
UIButton * (* clearButtonFunctionPointer)(id, SEL) = (void *)clearButtonImplementation;
// Set clearTextFieldButton reference to “clearButton” from clearButtonSelector
UIButton *_clearTextFieldButton = clearButtonFunctionPointer(self, clearButtonSelector);
[_clearTextFieldButton setImage:[UIImage imageNamed:@"icon_remove"] forState:UIControlStateNormal];
self.hasClearButtonAsRightView = YES;

now how to convert this to Swift? or any ideas to workaround it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...