【问题标题】:UIButton can't click after adding subViews添加子视图后UIButton无法点击
【发布时间】:2020-02-21 21:13:21
【问题描述】:

我在 UIButton 中添加了一个适合其内容的 subView,问题是我无法在单击它时听到按钮的操作,我的猜测是因为我的 UIButton 位于我添加的 subViews 的下方,但是不知道怎么解决。

这是我在按钮中添加子视图的代码

func setButtonContent(myButtonView: UIButton, textLabel: String, textViewDescription: String) {
    if let nibFile = Bundle.main.loadNibNamed("nibName", owner: self, options: nil)?.first as? FundTransferButton {
        nibFile.frame.size.height = myButtonView.frame.size.height
        nibFile.frame.size.width = myButtonView.frame.size.width
        nibFile.label.text = textLabel
        nibFile.textViewDescription.text = textViewDescription
        myButtonView.addSubview(nibFile)
    }
}

我只想创建一个包含我的自定义设计的自定义按钮。

【问题讨论】:

  • 我认为nibFile.isUserInteractionEnabled = false 应该可以解决它。
  • @Sweeper 对我有用,谢谢!我只是感到困惑,因为我在自动布局中取消选中我的 xib 文件根目录上的启用用户交互但没有发生任何事情,我接受它作为答案

标签: ios swift uibutton subview


【解决方案1】:

您的直接问题可以通过以下方式解决:

nibFile.isUserInteractionEnabled = false

这会使您添加的子视图不响应点击事件,因此点击事件“通过”子视图并“到达”按钮。

如果你只是想创建一个自定义的UIButton,你应该继承UIControlUIButton,并在xib文件中设计按钮本身。

【讨论】:

    【解决方案2】:

    您可以在 UIButton 的层下添加子视图层。

    myButtonView.insertSubview(nibFile, at: 0)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-11
      • 1970-01-01
      • 2011-10-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多