我正在尝试将按钮添加到我添加到主视图的以编程方式创建的视图中.我不能采取行动按钮.这是我到目前为止所尝试的:
itemView = UIImageView(frame:CGRect(x:0, y:0, width:240, height:375))
itemView.backgroundColor = UIColor(red: 255.0/0.0, green: 255.0/0.0, blue: 255.0/0.0, alpha: 0.05)
itemView.contentMode = .Center
buttonConnect = UIButton(frame: CGRect(x:0, y:335, width:120, height:40))
buttonConnect.backgroundColor = UIColor(red: 0.8, green: 0.6, blue: 0.2, alpha: 1.0)
buttonConnect.setTitle("Connect", forState: .Normal)
buttonConnect.tag = 3
buttonConnect.addTarget(itemView, action: "btnConnectTouched:", forControlEvents:.TouchDown)
itemView.addSubview(buttonConnect)
self.addSubview(itemView)
Run Code Online (Sandbox Code Playgroud)
按钮单击的方法如下所示:
func btnConnectTouched(sender:UIButton!)
{
print("button connect touched")
}
Run Code Online (Sandbox Code Playgroud)
有人可以建议问题是什么?谢谢!
我不明白你为什么要在UIImageView中添加一个按钮.即使这是你需要的,拿一个UIView,然后把所有其他控件放在里面.您的按钮未单击的原因是您将其放在UIImageView中,而对于UIImageView,userInteractionEnabled的默认值为false.所以你需要启用它,即
itemView.userInteractionEnabled = true;
Run Code Online (Sandbox Code Playgroud)
同时将按钮目标设置为"self"而不是itemView.