【问题标题】:Swift: "Attempt to present ViewController whose view is not in the window hierarchy" when using presentViewController inside a delegate methodSwift:在委托方法中使用 presentViewController 时,“尝试呈现其视图不在窗口层次结构中的 ViewController”
【发布时间】:2015-12-17 12:15:16
【问题描述】:

我正在使用一个带有按钮的自定义单元格类。

import UIKit

protocol TouchDelegateForShotsCell {
    func touchedTwitterButton()
}

class ShotsCell : UITableViewCell {

    let touchDelegateForShotsCell: TouchDelegateForShotsCell = MasterViewController()

    @IBAction func twitterButtonPressed(sender: AnyObject) {
         touchDelegateForShotsCell.touchedTwitterButton()
    }
}

当按下按钮时,我在 MasterViewController 中调用一个委托函数,其中包含以下用于在 Twitter 上共享的标准代码:

func touchedTwitterButton() {
    var shareToTwitter :SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeTwitter)
    self.presentViewController(shareToTwitter, animated: true, completion: nil)
}

我收到错误:

“尝试呈现其视图不在窗口层次结构中的 ViewController!”。

我尝试了几种解决方法。例如,创建一个单独的视图控制器并从按钮执行 segue。这部分有效,但是,当我尝试传递数据时,我得到另一个错误:

"'NSInvalidArgumentException',原因:接收方 ViewController 没有标识符为 'segueToTwitterShare' 的 segue"。

这不是真的。为此,我尝试删除我的应用程序并重新启动对某些人有用的 xcode。但是,问题仍然存在。

【问题讨论】:

    标签: ios iphone swift uitableview delegates


    【解决方案1】:
    let touchDelegateForShotsCell: TouchDelegateForShotsCell = MasterViewController()
    

    这不是好的delegate。当您编写MasterViewController() 时,您创建MasterViewController 的新实例(因此它不在窗口层次结构中),但您没有传递强烈的执行者 .

    我建议您举一个例子,以更好地了解问题所在并查看需要更改的地方。

    我在ShotsCell 中添加了一个init() 函数:

    class ShotsCell : UITableViewCell {
    
        var touchDelegateForShotsCell: TouchDelegateForShotsCell!
    
        init(withDelegate delegate: MasterViewController){
            super.init(style: UITableViewCellStyle.Default, reuseIdentifier: "cellIdentifier")
    
            touchDelegateForShotsCell = delegate
        }
    
        @IBAction func twitterButtonPressed(sender: AnyObject) {
            touchDelegateForShotsCell.touchedTwitterButton()
        }
    }
    

    然后将您的MasterViewController 传递到cellForRowAtIndexPath 中的单元格:

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = ShotsCell(withDelegate: self)
    
        return cell
    }
    

    希望对您有所帮助。它对我有用。

    【讨论】:

    • 感谢您的回答。 super.init() 不是指定的初始值设定项,因此我将其更改为 super.init(style: , reuseIdentifier: ) 但是当我输入样式和重用标识符的值时出现预期的错误“,”分隔符.
    • 你能发布一个示例项目的链接吗?
    • 我更新了答案以匹配您的代码,但是我无法重现此错误:将 super.init() 修改为 super.init(style:, reuseIdentifier:) 对我有用。
    猜你喜欢
    • 1970-01-01
    • 2019-06-10
    • 1970-01-01
    • 2015-09-17
    • 1970-01-01
    • 1970-01-01
    • 2017-07-27
    • 2014-06-01
    • 1970-01-01
    相关资源
    最近更新 更多