我正在以编程方式构建UIViews。如何在Swift中获取具有动作功能的UIButton?
以下代码不会得到任何操作:
let btn: UIButton = UIButton(frame: CGRectMake(100,400,100,50)) btn.backgroundColor = UIColor.greenColor() btn.setTitle("Click Me",forState: UIControlState.Normal) btn.addTarget(self,action: "buttonAction:",forControlEvents: UIControlEvents.TouchUpInside) self.view.addSubview(buttonPuzzle)
以下选择器功能是:
func buttonAction(sender: UIButton!) { var btnsendtag: UIButton = sender }
你只是错过了这个UIButton。为了补偿这一点,请更改其标签属性。
这是你回答:
这是你回答:
let btn: UIButton = UIButton(frame: CGRectMake(100,forControlEvents: UIControlEvents.TouchUpInside) btn.tag = 1 // change tag property self.view.addSubview(btn) // add to view as subview
Swift 3.0
let btn: UIButton = UIButton(frame: CGRect(x: 100,y: 400,width: 100,height: 50)) btn.backgroundColor = UIColor.green btn.setTitle(title: "Click Me",for: .normal) btn.addTarget(self,action: #selector(buttonAction),forControlEvents: .touchUpInside) btn.tag = 1 self.view.addSubview(btn)
这是一个示例选择器函数:
func buttonAction(sender: UIButton!) { var btnsendtag: UIButton = sender if btnsendtag.tag == 1 { //do anything here } }