0

我以编程方式创建了一个 UIButton 并将其添加到子视图中。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)
    }
}
4

2 回答 2

3

发生这种情况是因为您将按钮框架设置为 graterthen 您的视图,这就是您的按钮未点击的原因。

你没有设置你的视图框架,然后你怎么能在你的视图中设置你的按钮。

在这里,我更新了您的 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)
        }

我希望它对您有帮助并节省您的时间

于 2018-03-30T06:33:48.543 回答
1

您必须为您的 ViewSystem 提供框架。并且 ViewSystem 的高度宽度应该大于按钮的 X 和 Y。

    var ViewSystem = UIView()
ViewSystem.frame = CGRect(x: 50, y: 100, width: 70, height: 70)

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

func ButtonCreate () {

    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.addSubview(button)

    self.view.addSubview(ViewSystem)
    }
}
于 2018-03-30T06:27:38.103 回答