如何以编程方式创建UIButton

时间:2015-04-05 07:29:28

标签: swift uibutton

我正在尝试以编程方式构建UIView 。如何在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
}

3 个答案:

答案 0 :(得分:34)

您只是遗漏了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 属性 你在这里回答:

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)

Swift 3.0

func buttonAction(sender: UIButton!) {
    var btnsendtag: UIButton = sender
    if btnsendtag.tag == 1 {            
        //do anything here
    }
}

以下是一个示例选择器功能:

{{1}}

答案 1 :(得分: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
}

答案 2 :(得分:1)

您必须 btn addSubview 标记