2015-04-05 142 views
19

我正在尝试以编程方式构建UIView s 。如何在Swift中使用动作函数获得UIButton如何以编程方式创建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 
} 

回答

31

你只是缺少这UIButton这是。为了弥补这一点,请更改其tag属性。
这里是你回答:

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) 
btn.tag = 1    // change tag property 
self.view.addSubview(btn) // add to view as subview 

雨燕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 
    } 
} 
+0

感谢它的工作对我来说 – 2015-04-05 07:36:18

+2

如果sender.tag == 1 {...} – 2015-04-05 07:47:23

1

你必须addSubview标签btn

8

使用标签是一个脆弱的解决方案。您有一个观点,你是创建和添加按钮,该视图,你只需要一个参考保持它:例如

在你的类,保持对它的引用按钮

var customButton: UIButton! 

对这种情况下的动作功能创建按钮,设置参考

let btn = UIButton(frame: CGRect(x: 100, y: 400, width: 100, height: 50)) 
btn.backgroundColor = .greenColor() 
btn.setTitle("Click Me", forState: .Normal) 
btn.addTarget(self, action: #selector(MyClass.buttonAction), forControlEvents: .TouchUpInside) 
self.view.addSubview(btn) 
customButton = btn 

测试

func buttonAction(sender: UIButton!) { 
    guard sender == customButton else { return } 

    // Do anything you actually want to do here 
} 
+1

很轻微,但你之前'='这里btn'后'忘空间:'让BTN =的UIButton。 ..' – damianesteban 2016-01-27 19:36:03

+0

谢谢,现在修复。 – Abizern 2016-01-27 20:13:05