我想添加按鈕到編程方式創建的視圖,我添加到主視圖。我無法採取行動來處理按鈕。這是我試過到目前爲止:按鈕點擊Swift將按鈕添加到視圖編程方式與動作
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)
方法是這樣的:
func btnConnectTouched(sender:UIButton!)
{
print("button connect touched")
}
可有人建議這是什麼問題?謝謝!
這是一個很好的答案。非常感謝!我將'UIImageView'改爲'UIView',並且將目標改爲'self',並且它可以工作 – bla0009