我想在UITextField上创建自定义清除按钮,即使用rightView并将图像放在此处,问题是将原始的清除按钮事件附加到该自定义rightView上。
在Objective-C中,我可以这样做:
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?或任何解决方法?
您可以将自定义按钮添加为UITextField类似这样的右视图
UITextField
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) } }