【问题标题】:How to create a UIButton programmatically如何以编程方式创建 UIButton
【发布时间】:2015-04-05 07:29:28
【问题描述】:

我正在尝试构建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
}

【问题讨论】:

    标签: swift uibutton


    【解决方案1】:

    您只是错过了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
    

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

    【讨论】:

    • 如果 sender.tag == 1 { ... }
    【解决方案2】:

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

    在您的班级中,保留对按钮的引用

    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
    }
    

    【讨论】:

    • 非常小,但是您忘记了btn 之后和= 之前的空格:let btn= UIButton...
    【解决方案3】:

    你必须在那个btnaddSubviewtag

    【讨论】:

      猜你喜欢
      • 2010-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多