Ios 斯威夫特:“我的名字叫什么?”;尝试显示视图不在窗口层次结构中的ViewController“;在委托方法内使用presentViewController时

Ios 斯威夫特:“我的名字叫什么?”;尝试显示视图不在窗口层次结构中的ViewController“;在委托方法内使用presentViewController时,ios,iphone,swift,uitableview,delegates,Ios,Iphone,Swift,Uitableview,Delegates,我正在使用一个自定义单元格类,其中有一个按钮 import UIKit protocol TouchDelegateForShotsCell { func touchedTwitterButton() } class ShotsCell : UITableViewCell { let touchDelegateForShotsCell: TouchDelegateForShotsCell = MasterViewController() @IBAction fun

我正在使用一个自定义单元格类,其中有一个按钮

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!”

我试过几种变通方法。例如,创建单独的视图控制器并从按钮执行分段。但是,当我尝试传递数据时,会出现另一个错误:

“'NSInvalidArgumentException',原因:接收器ViewController没有标识符为'SegueTowitterShare'的segue”

这不是真的。为此,我尝试删除我的应用程序并重新启动xcode,这对一些人来说是有效的。然而,问题依然存在

let touchDelegateForShotsCell: TouchDelegateForShotsCell = MasterViewController()
这不是好的
代表
。编写
MasterViewController()
时,您创建了
MasterViewController
的一个新实例(因此它不在窗口层次结构中),但不会传递执行的对象

我建议您举个例子,以便更好地了解问题所在,并了解需要进行哪些更改

我将
init()
函数添加到
ShotsCell

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()
    }
}
并将您的
主视图控制器
传递到
cellforrowatinexpath
中的单元格:

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

    return cell
}

希望有帮助。这对我很有用。

谢谢你的回答。super.init()不是指定的初始值设定项,因此我将其更改为super.init(样式:,reuseIdentifier:),但得到了预期的错误“,'当我为style和reuseIdentifier输入值时使用分隔符。您可以发布一个到示例项目的链接吗?我更新了答案以匹配您的代码,但无法重现此错误:将
super.init()
修改为
super.init(style:,reuseIdentifier:)
对我有效。