我以编程方式创建了一个 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)
}
}