我在文本字段的 leftView 上有一个图标,我想向其添加点击手势。这是我的代码:
if (!textField.leftView){
UIImageView *infoImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30, 18)];
infoImage.image = [UIImage imageNamed:@"info"];
infoImage.contentMode = UIViewContentModeCenter;
textField.leftView = infoImage;
textField.leftViewMode = UITextFieldViewModeAlways;
UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showErrorMessage:)];
tapRecognizer.numberOfTapsRequired = 1;
[infoImage addGestureRecognizer:tapRecognizer];
}
当用户单击左视图上的图像时,问题没有发生,并且
showErrorMessage
没有被调用。
更新
通过在 infoImage 上启用 userInteraction 解决了点击问题。
但现在我在节目第二行得到了
[UITapGestureRecognizer tag]: unrecognized selector sent to instance
errorMessage
:
-(void)showErrorMessage:(id)sender{
UIImageView *icon = (UIImageView *)sender;
NSString *key = [@(icon.tag) stringValue];
NSLog(@"%@", [_errorDictionary objectForKey:key]);
}
失踪了
infoImage.userInteractionEnabled = YES;
您必须将图像的属性 userInteractionEnabled 设置为 TRUE
添加 leftView 和点击手势的完整 Swift 代码:
extension UITextField {
func setLeftIcon(_ image: UIImage) {
let iconView = UIImageView(frame:
CGRect(x: 10, y: 5, width: 20, height: 20))
iconView.image = image
let iconContainerView: UIView = UIView(frame:
CGRect(x: 20, y: 0, width: 30, height: 30))
iconContainerView.addSubview(iconView)
leftView = iconContainerView
leftViewMode = .always
}
}
override func viewDidLoad() {
super.viewDidLoad()
myTextfield.setLeftIcon(UIImage(named: "imageName"))
myTextfield.leftView?.addTapGesture(target: self, selector: #selector(methodName))
}