@IBAction func getNewPhotoAction(sender: AnyObject) {
println("getNewPhotoAction")
}
override func viewDidLoad() {
super.viewDidLoad()
self.getNewPhotoAction(sender: AnyObject) // Error
}
我只想在viewDidLoad
中调用getNewPhotoAction
IBAction 方法。
在此行中输入哪个参数 -> self.getNewPhotoAction(?????)
?
我没有任何参数。我只需要打电话。
我以Objective-C风格使用:
[self getNewPhotoAction:nil]
但我不知道斯威夫特的风格。
参数 sender
指示谁在调用操作方法。从viewDidLoad
呼叫时,只需将self
传递给它即可。
override func viewDidLoad() {
super.viewDidLoad()
getNewPhotoAction(self)
}
顺便说一下,如果未使用 getNewPhotoAction
方法的 sender
参数,则可以省略参数名称。
@IBAction func getNewPhotoAction(AnyObject) {
println("getNewPhotoAction")
}
您始终可以在 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()
}
Swift 4.2
@IBAction func getNewPhotoAction(sender: Any) {
println("getNewPhotoAction")
}
override func viewDidLoad() {
super.viewDidLoad()
self.getNewPhotoAction(AnyObject.self)
}
如果您仍然需要引用UIButton
或发送操作的任何内容,并希望同时从代码调用它 - 您也可以这样做:
onNext(UIButton())
浪费,但代码更少。
@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)
你实际上根本不需要传递any object
。如果你不需要使用 sender
,那么在没有它的情况下声明function
,如下所示:
@IBAction func getNewPhotoAction() { ... }
并像这样使用它:
self.getNewPhotoAction()
如果此方法连接到 interface builder
中的事件,则在进行此更改(将其删除,然后重新添加(时,可能需要重新连接 interface builder
中的插座。
@IBAction func getNewPhotoAction(sender: AnyObject? = nil) {
print("getNewPhotoAction")
}
override func viewDidLoad() {
super.viewDidLoad()
self.getNewPhotoAction(nil)
}
由于您没有任何发件人,请交出nil
。
self.getNewPhotoAction(nil)