【发布时间】:2018-03-30 06:02:51
【问题描述】:
我以编程方式创建了一个 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)
}
}
【问题讨论】:
-
可以添加button.isUserInteractionEnabled = true
-
尝试 ViewSystem.clipsToBounds = true。我相信你不会看到你的按钮
-
你没有指定
ViewSystem的框架
标签: swift uibutton subview addtarget