自定义清除按钮 [英] Custom Clear Button

查看:153
本文介绍了自定义清除按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在UITextField上创建自定义清除按钮,即使用rightView并将图像放在那里,问题是将原始清除按钮事件附加到该自定义rightView。

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.

在Objective-C中我可以这样做:

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;

现在如何将此转换为Swift?
或任何解决方法吗?

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

推荐答案

您可以添加自定义按钮作为<$ c的右视图$ c> UITextField 喜欢这个

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: CGRectMake(0, 0, 15, 15))
        clearButton.setImage(UIImage(named: "clear.png")!, forState: UIControlState.Normal)

        self.rightView = clearButton
        clearButton.addTarget(self, action: "clearClicked:", forControlEvents: UIControlEvents.TouchUpInside)

        self.clearButtonMode = UITextFieldViewMode.Never
        self.rightViewMode = UITextFieldViewMode.Always
    }

    func clearClicked(sender:UIButton)
    {
        self.text = ""
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}

这篇关于自定义清除按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆