Swift 如何以编程方式创建UIButton

Swift 如何以编程方式创建UIButton,swift,uibutton,Swift,Uibutton,我正在尝试以编程方式构建UIViews。如何在Swift中获得带有动作功能的ui按钮 以下代码未获得任何操作: 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

我正在尝试以编程方式构建
UIView
s。如何在Swift中获得带有动作功能的
ui按钮

以下代码未获得任何操作:

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
}

您只是缺少了这是哪个
ui按钮。要对此进行补偿,请更改其
标记
属性。
以下是你的答案:

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
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
    }
}

您必须添加子视图标记,使用标记是一个脆弱的解决方案。您有一个视图,并且您正在创建该视图并将该按钮添加到该视图中,您只需要保留对该视图的引用:例如

在您的课堂上,保留对按钮的引用

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

    // Do anything you actually want to do here
}
创建按钮并设置参考

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
在操作函数中测试此实例

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

    // Do anything you actually want to do here
}

如果sender.tag==1{…}非常小,但您忘记了
btn
之后和
=/code>之前的空格,则此处:
让btn=ui按钮…