如何在未按下按钮时调用按钮功能

时间:2015-05-01 12:19:33

标签: ios swift swift2 ibaction

我有一个IBAction连接到一个按钮,我想知道是否有任何方法可以运行该功能,即使没有按下该按钮。这就是我试过的......

注意:我在这个项目中使用swift。

//I get an error when I type this code?
self.buttonPressed()

@IBAction func buttonPressed(sender: AnyObject) {

    print("Called Action")

}

5 个答案:

答案 0 :(得分:12)

使您的发件人参数可选,并将nil传递给ButtonPressed。

self.ButtonPressed( nil )


@IBAction func ButtonPressed( sender: AnyObject? ) {
    println("Called Action")
}

答案 1 :(得分:8)

一种方法是将您的按钮链接到相应的界面构建器按钮,并在调用它时将其传递给您的功能。

@IBOutlet weak var yourButton: UIButton!

// When you call method
self.buttonPressed(yourButton)

//function must begin with small letter as per iOs naming convention
@IBAction func buttonPressed(sender: AnyObject) {
    //println("Called Action"). This method has been renamed to print() in Swift 2.0
    print("Called Action")
}

或者,像这样定义你的函数,然后你就可以像以前一样调用你的方法了:

@IBAction func buttonPressed(sender: AnyObject? = nil) {
    print("Called Action")
}

//Call your method like this
self.buttonPressed()

答案 2 :(得分:0)

您需要将“self”用作“发件人”,例如:

self.buttonPressed (sender: self)

或更简单的版本

buttonPressed (sender: self)

两者都在Swift 3中测试

答案 3 :(得分:0)

使用以下格式调用按钮操作:Swift 3

@IBAction func buttonSelected(_ sender: UIButton) {
        print("Butten clicked")
}

调用按钮操作:

let button = UIButton()
self.buttonSelected(button)

答案 4 :(得分:0)

    lazy var Button : UIBarButtonItem = {
      let barButtonItem = UIBarButtonItem(title: "Button", style: .done, target: self, action: #selector(btnSelection))
      return barButtonItem
    }()


    func btnSelection(){
     // Code
    }

    // Now you can call self.btnSelection() whenever you want