我有一个函数,我想在按下按钮时调用它,但与我迄今为止所做的任何事情不同,我希望能够从多个 ViewController 中的任何一个访问它。我不想在每个 ViewController 中重复相同的代码块。
我尝试在 ViewController 类之外定义我想要调用的函数,但我无法弄清楚我需要将目标设置为什么才能达到它。通常self
使用该函数是因为该函数是在类中定义的,但是如果该函数在另一个文件中和/或在类外部,您该怎么办?
button.addTarget(???, action: "myFunction:", forControlEvents: UIControlEvents.TouchUpInside)
编辑:我可以使用的另一个解决方案是执行类似的操作并定义我想要在创建按钮的函数内部调用的函数,但我遇到了同样的问题,不知道该函数是什么target
需要达到它。
class ViewController {
// Main code here
}
func makeButton() {
// Code to make button here
button.addTarget(???, action: "buttonPressed",...)
func buttonPressed() {
// Code that runs when the button is pressed goes here
}
}
提前致谢!
您可以在这里找到完整的教程。https://github.com/fatihyildizhan/SingletonFunctionForAddTarget https://github.com/fatihyildizhan/SingletonFunctionForAddTarget
如果你不想下载它:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var btnGotoVacation: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
btnGotoVacation.addTarget(MySingletonClass.sharedInstance, action: Selector("visitBodrum:"), forControlEvents:.TouchUpInside)
}
}
class MySingletonClass:NSObject {
static let sharedInstance = MySingletonClass()
func visitBodrum(sender:AnyObject) {
print("don't forget to visit yalikavak :) ")
}
}
关键是你应该inherit your singleton class
from NSObject
.
if not you'll probably get this error:
如果你这样做:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)