【问题标题】:UIButton in UIView subclass not triggeringUIView 子类中的 UIButton 未触发
【发布时间】:2021-10-24 04:47:43
【问题描述】:

我试图将一个按钮作为此 UIView 子类的子视图,但单击时未触发按钮操作,我在这里做错了什么导致它无法触发吗?它显示按钮和所有内容,但操作不起作用。自定义 UIView 子类嵌套在自定义结构中

class TakeAvatarView: UIView {
    
    var delegate:SingleTakeDelegate?

    var agree = false

    convenience init(frame: CGRect, agree: Bool, last: Bool) {
        self.init(frame: frame)
        self.agree = agree
        if !last {
            avatarNode()
        } else {
            lastNode()
        }
     }


     func lastNode(){
        let button = UIButton(frame: CGRect(x: 2, y: 2, width: 26, height: 26))
        button.setTitle("+10", for: .normal)
        button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 12)
        button.setTitleColor(.lightGray, for: .normal)
        button.addTarget(self, action: #selector(showMoreTapped), for: .touchUpInside)
        button.isUserInteractionEnabled = true
        self.layer.borderWidth = 1.0
        self.layer.borderColor = UIColor.lightGray.cgColor
        self.addSubview(button)
    }
    
    @objc func showMoreTapped(){
        delegate?.showParticipantsPressed(agree: self.agree)
    }
}

【问题讨论】:

  • 您确定设置了delegate 吗?现在,像delegate?.show... 这样使用它只会默默地失败。
  • 我在showMoreTapped() 中检查了一个断点并没有触发任何事件,即使委托失败,操作也不起作用
  • 我刚刚在模拟器上的一个空应用程序中尝试了您的示例 - showMoreTapped() 中的断点命中
  • 可能是因为 UIView 子类嵌套在一个结构体中?
  • 你的视图是 UITableViewCell 的子视图吗?

标签: ios swift uiview uibutton


【解决方案1】:

你做的一切都正确,确保

  1. 你称它为 lastNode()
  2. var 委托:SingleTakeDelegate? 已设置,你应该使用弱引用。 https://medium.com/macoclock/delegate-retain-cycle-in-swift-4d9c813d0544

我在操场上测试了你的代码,它可以工作

【讨论】:

  • lastNode() 被调用,委托不是问题,尽管设置断点表明 showMoreTapped 没有被触发
  • 会不会是因为 UIView 子类是从结构体中添加的?
  • 也许您确实将 isUserInteractionEnable 设置为 superview?
  • 你能给出完整的代码吗?或链接到 GitHub?
  • userInteraction 开启,我贴代码
猜你喜欢
  • 1970-01-01
  • 2019-09-04
  • 1970-01-01
  • 2018-01-19
  • 2023-04-03
  • 2021-12-29
  • 1970-01-01
  • 1970-01-01
  • 2018-06-09
相关资源
最近更新 更多