【问题标题】:iOS Button not work in custom viewiOS Button 在自定义视图中不起作用
【发布时间】:2023-03-26 14:02:02
【问题描述】:

有两个自定义视图 - viewA 和 viewB。ViewB 是在 viewA 中添加的一个小视图。起初 viewA 充满了整个屏幕。 ViewB 位于 viewA 的底部(屏幕外)。当点击 viewA 中的按钮时,viewB 的约束底部常量将为 -100,因此 viewB 将显示在屏幕底部。但是viewB中有一个按钮没有响应它的选择器。这是我的代码:

在视图A中

let viewB: ViewB = {
    let view = ViewB(
    view.setup()
    return view
}()

viewB 约束:

    viewB.snp.makeConstraints { (make) in
        make.trailing.leading.equalTo(self)
        make.height.equalTo(100)
        make.top.equalTo(self.snp.bottom)
    }

当点击按钮引起视图B

            UIView.animate(withDuration: 0.5) {
            self.snp.updateConstraints({ (make) in
                make.bottom.equalTo(-100)
            })
        }
        self.layoutIfNeeded()

在视图B中:

class ViewB: UIView {

let b: UIButton = {
    let button = UIButton(type: UIButtonType.custom)
    button.addTarget(self, action: #selector(btnClicked), for: UIControlEvents.touchUpInside)
    button.backgroundColor = UIColor.green
    button.setTitle("Button", for: .normal)
    return button
}()


func btnClicked() {
   print("btnClicked")
}

func setup() {
    addSubview(b)
    b.snp.makeConstraints { (make) in
        make.leading.top.bottom.equalTo(self)
        make.width.equalTo(100)
    }

}
}

【问题讨论】:

  • 你设置的按钮框架的代码在哪里?
  • button.frame = CGRect(button_x_position,Button_y_position,your_button_width , your_button_hight) 在 let button = UIButton(type: UIButtonType.custom) 之后添加这一行并检查输出
  • 按钮是否可见?如果是,请检查调试视图层次结构中是否有另一个视图与您的 UIButton 重叠。

标签: ios swift uiview uibutton


【解决方案1】:

您的代码本身可以正常工作。因此,问题可能类似于按钮被另一个执行触摸操作的视图覆盖。您可以使用视图调试器对此进行测试,或者提供指向您的项目的链接,以便我们中的一个人可以看看发生了什么。

【讨论】:

  • 好的,如果您无法找出问题所在,那么我建议发布一个指向完整项目的链接(不仅仅是代码 sn-ps),以便我(或其他人)可以运行项目并告诉你出了什么问题。
  • 感谢您,我发现 viewB 超出了边界。
  • 很高兴听到您能够自己解决问题 :) 这些总是最好的情况 - 至少对我而言。
【解决方案2】:

我认为,您的视图正在超出其超级视图或任何其他视图正在其上层出现。请看这个

superview.clipsToBounds :  YES

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-28
    • 1970-01-01
    相关资源
    最近更新 更多