从视图控制器调用应用程序委托方法
我想知道是否可以从另一个ViewController调用应用程序委托方法。
当应用程序启动时, application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
i方法被调用。 我可以从另一个视图控制器第二次调用这个方法吗?
不知道你为什么要这样做。 你可能不应该,但为了回答这个问题的目的是这样的:
// get a reference to the app delegate let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate // call didFinishLaunchWithOptions ... why? appDelegate.application(UIApplication.sharedApplication(), didFinishLaunchingWithOptions: nil)
在Swift 3.0中,你可以调用:
let appDelegate = UIApplication.shared.delegate as! AppDelegate appDelegate.anyAppDelegateInstaceMethod()
这个方法在应用程序启动时只调用一次。 你不能从ViewController。 而是在AppDelegete中创build用户定义的方法。 并从ViewController中调用该方法。 通过获取AppDelegate的对象。
AppDelegate *appDel = (AppDelegate *)[UIApplication sharedApplication].delegate; [appDel <Your method>];
构造函数:
在代码结尾添加一个AppDelegate类的构造函数
Swift 3.x
class func shared() -> AppDelegate { return UIApplication.shared.delegate as! AppDelegate }
Swift 2.x
func appDelegate () -> AppDelegate { return UIApplication.sharedApplication().delegate as! AppDelegate }
并添加一个这样的变种
var boolForFun = Bool()
如何在课堂上使用参考?
方法
用于快速的3x访问function或variables
AppDelegate.shared().boolForFun = true
为了别的
appDelegate().methodFoo()
variables
appDelegate().foo
- 内存泄漏时使用NSURLSession.downloadTaskWithURL
- 从Xcode 7 UItesting目标访问主机应用程序代码
- 带有Aspect的UIImageView使用AutoLayout填充自定义的UITableViewCell
- 如何在Swift 2.0中创build一个dispatch_block_t数组?
- 如何知道两个表情符号是否会显示为一个表情符号?
- iOS使用QuickTime播放器检测/屏蔽屏幕录制
- 当Autolay正在播放时,用UIDynamicAnimator进行animation处理
- 如何在GitHub for iOS(SWIFT)项目中隐藏API密钥?
- 遍历.plist字典。 types不匹配