在Swift 3.0中向UIButton添加操作时出现问题

时间:2016-09-17 06:26:27

标签: ios swift uibutton swift3

我正在UIButton以编程方式创建swift 3

但我无法向其添加动作。

     //Adding BUtton
    let btn = UIButton()

    btn.frame = CGRect(x: 100, y: 100, width: 200, height: 100)

    btn.addTarget(self, action: #selector(self.printname()), for: UIControlEvents.touchUpInside)

    self.view.addSubview(btn)

    //Method to be called
    func printname()
    {
        print("button pressed")
    }

我在上面的代码中做错了什么?

修改

现在我正在使用此代码:

     btn.addTarget(self, action: #selector(self.printname(sender:)), for:.touchUpInside)


      func printname(sender: UIButton)
      {
         print("button pressed")
      }

      When I select Button this method is never called.

2 个答案:

答案 0 :(得分:0)

//Adding BUtton
let btn = UIButton(frame: CGRect(x: 100, y: 100, width: 200, height: 100))
btn.backgroundColor = UIColor.clearColor()
btn.setTitle("Test Button", forState: .Normal)
btn.addTarget(self, action: #selector(printname), forControlEvents: .TouchUpInside)

self.view.addSubview(btn)

//button action
func printname (){
  print("button pressed")
}

答案 1 :(得分:0)

当您将该方法作为选择器传递时,您不需要将()添加到方法的末尾!这是因为{<1}}用于在调用方法时指定参数。但你不想打电话给这个方法,对吗?所以删除()

()

这与将闭包传递给方法相同:

 //Adding BUtton
let btn = UIButton()

btn.frame = CGRect(x: 100, y: 100, width: 200, height: 100)

// () removed!
btn.addTarget(self, action: #selector(self.printname), for: UIControlEvents.touchUpInside)

self.view.addSubview(btn)

//Method to be called
func printname()
{
    print("button pressed")
}

无论传入的方法中有多少个参数,都是如此。

编辑:我刚看到你的doStuff(withClosure: myMethod) func myMethod() { // ... } 方法似乎在另一个方法中。如果是这样,请将其移至班级!此外,您需要向printname添加sender参数:

printname