如何为代码创建的UIView添加点击手势?求助排查问题
问题排查与修复
你遇到的点击手势无效问题,存在两处关键问题:
1. 自定义PaymentServiceView本身无有效可点击区域
你的PaymentServiceView内部创建了views子视图并设置了固定宽高(320x150),但未给PaymentServiceView自身添加尺寸约束,导致PaymentServiceView的实际frame为CGRect.zero——视图本身没有可点击的物理区域,手势自然无法触发。
修复方法
在PaymentServiceView的setupConstraints方法末尾,添加约束让自身尺寸与内部views完全匹配:
// 绑定PaymentServiceView与内部views的尺寸 self.topAnchor.constraint(equalTo: views.topAnchor).isActive = true self.bottomAnchor.constraint(equalTo: views.bottomAnchor).isActive = true self.leadingAnchor.constraint(equalTo: views.leadingAnchor).isActive = true self.trailingAnchor.constraint(equalTo: views.trailingAnchor).isActive = true
2. 手势添加时的笔误
在PaymentServicesViewController的viewDidLoad中,给billPaymentView添加手势时,错误地给fundTransferView重复设置了交互属性:
let billPaymentGesture = UITapGestureRecognizer(target: self, action: #selector(billPaymentTapped)) fundTransferView.isUserInteractionEnabled = true // 此处应为billPaymentView self.billPaymentView.addGestureRecognizer(billPaymentGesture)
修复方法
将该行修正为:
billPaymentView.isUserInteractionEnabled = true
完成以上两处修复后,点击手势即可正常触发。
内容的提问来源于stack exchange,提问作者Ahmed Saeed
相关产品推荐
相关产品推荐

