gpt4 book ai didi

UIButton 的 Swift addTarget 在 UIView 中不起作用

转载 作者:行者123 更新时间:2023-11-28 10:09:43 25 4
gpt4 key购买 nike

我以编程方式创建了一个 UIButton 并将其添加到 subview 。 AddTarget 在那里不起作用。 AddTarget 只有在我将按钮添加到主视图时才有效。

self.view.addSubview(button)

代替

ViewSystem.addSubview(button)

没有人知道为什么吗?

完整代码如下:

class ViewController: UIViewController {

var ViewSystem = UIView()
@objc func TestPressed(sender: UIButton?) {Test.text=String((sender?.tag)!)

func ButtonCreate () {

let button = UIButton()
button.frame = CGRect(x: 50, y: 100, width: 70, height: 70)
button.addTarget(self, action: #selector(TestPressed), for: .touchUpInside)
button.backgroundColor = UIColor.red
button.tag=5
ViewSystem.addSubview(button)

self.view.addSubview(ViewSystem)
}
}

最佳答案

发生这种情况是因为您设置了按钮框架,然后查看了您的 View ,这就是为什么您的按钮没有被点击。

您没有设置 View 框架,然后如何在 View 内设置按钮。

我在这里更新了您的 ButtonCreate () 函数代码,它运行良好。

func ButtonCreate () {
ViewSystem.frame = CGRect(x: 50, y: 100, width: 200, height: 70)
ViewSystem.backgroundColor = .blue
let button = UIButton()
button.frame = CGRect(x: 0, y: 0, width: 70, height: 70)
button.addTarget(self, action: #selector(TestPressed), for: .touchUpInside)
button.backgroundColor = UIColor.red
button.tag = 5
ViewSystem.clipsToBounds = false
ViewSystem.addSubview(button)

self.view.addSubview(ViewSystem)
}

希望对您有所帮助,节省您的时间

关于UIButton 的 Swift addTarget 在 UIView 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49569229/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com