Swift - 在没有参数的viewDidLoad中调用@IBAction方法

时间:2014-10-13 21:49:33

标签: swift parameters ibaction

@IBAction func getNewPhotoAction(sender: AnyObject) {
    println("getNewPhotoAction")
}

override func viewDidLoad() {
    super.viewDidLoad()
    self.getNewPhotoAction(sender: AnyObject) // Error
}

我只想在getNewPhotoAction中调用viewDidLoad IBAction方法。

在此行中输入哪个参数 - > self.getNewPhotoAction(?????)

我没有任何参数。我只需要打电话。

我用的是Objective-C风格:

[self getNewPhotoAction:nil]

但我不知道斯威夫特的风格。

8 个答案:

答案 0 :(得分:38)

参数sender表示调用操作方法的人员。 从viewDidLoad致电时,只需将self传递给它。

override func viewDidLoad() {
    super.viewDidLoad()
    getNewPhotoAction(self)
}

顺便说一下,如果未使用sender方法的getNewPhotoAction参数,则可以省略参数名称。

@IBAction func getNewPhotoAction(AnyObject) {
    println("getNewPhotoAction")
}

答案 1 :(得分:5)

您始终可以创建一个单独的func,您可以在viewDidLoad或IBAction中调用

override func viewDidLoad() {
   super.viewDidLoad()
   self.getNewPhoto()
}

func getNewPhoto(){
    //do whatever you want here. 
    println("getnewphotoaction")
    println("whatever you want")
}
@IBAction func getNewPhotoAction(sender: AnyObject) {
    self.getNewPhoto()
}

答案 2 :(得分:3)

如果您仍需要引用UIButton或发送操作的任何内容,并希望同时从代码中调用它 - 您也可以这样做:

onNext(UIButton())

浪费,但代码较少。

答案 3 :(得分:2)

你实际上根本不需要通过any object。如果您不需要使用sender,请在不使用function的情况下声明@IBAction func getNewPhotoAction() { ... }

self.getNewPhotoAction()

并像这样使用它:

interface builder

如果此方法已连接到interface builder中的某个事件,则可能需要在进行此更改时将其重新连接到{{1}}中的插座(将其删除,然后重新添加)。

答案 4 :(得分:2)

@IBAction func getNewPhotoAction(sender: AnyObject?){
    ......
}

**AnyObject** means that you have to pass kind of Object which you are using, nil is not a AnyObject.
But **AnyObject?**, that is to say AnyObject is Optional, nil is a valid value.
meaning the absence of a object.

self .getNewPhotoAction(nil)

答案 5 :(得分:1)

@IBAction func getNewPhotoAction(sender: AnyObject? = nil) {
    print("getNewPhotoAction")
}

override func viewDidLoad() {
    super.viewDidLoad()
    self.getNewPhotoAction(nil)
}

答案 6 :(得分:1)

Swift 4.2

@IBAction func getNewPhotoAction(sender: Any) {
    println("getNewPhotoAction")
}

override func viewDidLoad() {
    super.viewDidLoad()
    self.getNewPhotoAction(AnyObject.self)
}

答案 7 :(得分:0)

由于您没有任何发件人,请移交nil

self.getNewPhotoAction(nil)