如何快速获取全局指针到视图控制器 [英] How to get global pointer to view controller in swift

查看:41
本文介绍了如何快速获取全局指针到视图控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 swift 构建一个应用程序.在我的应用程序中,我需要呈现一个 UIPopoverPresentationController,并且我还需要从我的普通视图控制器中的其他方法访问该弹出窗口中的内容控制器.

I'm building an app using swift. In my app, I need to present a UIPopoverPresentationController, and I also need to acces the content controller from that popover from other methods in my normal view controller.

为此,我通常会在目标 C 中创建一个指向我的视图控制器的全局指针,这将允许我从任何方法访问它.

To do this, I would normally in objective C just create a global pointer to my view controller, which would allow me to access it from any method.

这就是我在 Swift 中的做法:

This is how I would do it in Swift:

class Categories: UITableViewController, UIPopoverPresentationControllerDelegate {

let storyBoard = UIStoryboard(name: "Main", bundle:nil)
var newCategory = self.storyBoard.instantiateViewControllerWithIdentifier("NewCategory") as NewCategory

//rest of my code

当我这样做时,Xcode 给了我错误:

When I do this, Xcode gives me the error:

Categories.type does not have a member named 'storyBoard'

谁能告诉我我做错了什么以及我需要如何修改我的代码以创建一个指向我的视图控制器的合法全局指针?任何帮助将不胜感激!

Can anybody tell me what I'm doing wrong and how I need to modify my code to create a legit global pointer to my view controller? Any help would be highly appreciated!

推荐答案

你应该为此使用@lazy 属性.波纹管是一般收据:

You should use @lazy attribute for this. Bellow is general receipt:

class MyClass {
    let compileTimeProperty = "compileTimePropert"

    @lazy var runTimeProperty:String = {
        return self.compileTimeProperty
    }()
}

这里是你的代码应该如何调整:

And here is how your code should be adjusted:

class Categories: UITableViewController, UIPopoverPresentationControllerDelegate {

    let storyBoard = UIStoryboard(name: "Main", bundle:nil)

    @lazy var newCategory: NewCategory = {
        return self.storyBoard.instantiateViewControllerWithIdentifier("NewCategory") as NewCategory
    }()

    //rest of your code
}

这篇关于如何快速获取全局指针到视图控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆