ios - SWIFT:如何使用不同类的performSegueWithIdentifier

标签 ios swift segue

我正在尝试让我的应用程序在 2 分钟不活动后自动返回主菜单。到目前为止,我的两个部分都可以工作,但不能一起工作..

如果没有触摸输入,应用程序将启动计数器:

查看用户4806509对Detecting when an app is active or inactive through touches in Swift的回答

从我的主视图 Controller 中,我可以使用代码控制我需要的segue:

func goToMenu()
{
    performSegueWithIdentifier("backToMenu", sender: self)
}

我已经实现了 Rob 在 How to call performSegueWithIdentifier from xib? 上的回答中的代码

所以我创建了以下类和协议(protocol):

protocol CustomViewDelegate: class {
    func goToMenu()
}
class CustomView: UIView
{
weak var delegate: CustomViewDelegate?
    func go() {
        delegate?.goToMenu()
    }
}

当定时器超时时,函数 go() 被(成功)调用。但是 delegate?.goToMenu() 不起作用。如果我将其更改为: delegate!.goToMenu(),则应用程序崩溃并显示:

fatal error: unexpectedly found nil while unwrapping an Optional value

我的主视图 Controller 是一个 CustomViewDelegate,viewDidLoad 包含:

let myCustomView = NSBundle.mainBundle().loadNibNamed("customView", owner: self, options: nil)[0] as! CustomView
myCustomView.delegate = self

我有正确的 xib 文件,并且该部分正在工作。

我似乎无法找到这个看似简单的问题的解决方案,有人可以解决吗?或者更好的是,有一个更优雅的解决方案来解决我的问题?

谢谢!

编辑:解决方案:

我删除了所有旧代码并实现了 NSNotification 方法:

在 UIApplication 中:

let CallForUnwindSegue = "nl.timfi.unwind"

func delayedAction()
{
    NSNotificationCenter.defaultCenter().postNotificationName(CallForUnwindSegue, object: nil)
}

在主视图 Controller 中:

let CallForUnwindSegue = "nl.timfi.unwind"
func goToMenu(notification: NSNotification) 
{
    performSegueWithIdentifier("backToMenu", sender: self)
}
deinit 
{
    NSNotificationCenter.defaultCenter().removeObserver(self)
}

在 viewDidLoad 中: NSNotificationCenter.defaultCenter().addObserver(self, 选择器: #selector(PeriodViewController.goToMenu), name:CallForUnwindSegue , object: nil)

最佳答案

我相信你的问题是,因为你的委托(delegate)被声明为弱变量,所以当你等待计时器完成时,你的委托(delegate)被释放,因此对可选的引用丢失(当你强制展开时返回 nil它)。

尝试从 CustomView 类中删除weak关键字。

另一个解决方案是使用通知中心通知您的 View 调用 segue。

与我提议的内容类似here

我希望这会有所帮助。

关于ios - SWIFT:如何使用不同类的performSegueWithIdentifier,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37780310/

相关文章:

ios - View Controller 无法找到带有标识符的 Segue

ios - Xcode 6 Storyboard Unwind Segue with Swift 不连接退出

ios - 如何将 Controller 转换为特定协议(protocol)而不是 Swift 中的类?

ios - 在 Swift 中智能搜索解析用户名不起作用

ios - 我如何使用 uitableview 单元格来执行 segue

objective-c - iOS 6,转场 : prepareForSegue doesn't get called when tapping on UITableViewCell at first time

objective-c - Xcode - 何时使用 UIView 或 UITableView?

ios - avplayer 在 ios 4.3 中不工作

ios - 更新核心数据的正确方法

xcode - 使用 Swift 通过 iPhone 扬声器强制播放音频文件