1

我正在尝试设置主详细信息导航。我使用storyboard,master是动态表,details是静态表。 故事板 我在控制器中有一个 nameLabel 设置作为插座,但是当我尝试在 viewDidLoad 中访问它时,它仍然设置为 nil。

我没有使用prepareForSegue,而是使用了didSelectRowAtIndexPath,它像这样推送详细视图:(因为我使用的是TableViewBindingHelper,请参阅https://github.com/ColinEberhardt/ReactiveTwitterSearch/tree/master/ReactiveTwitterSearch/Util

    func showLessonView(lessonVM: LessonViewModel) {

        let lessonViewController = LessonViewController(WithViewModel: lessonVM)
        self.navigationController?.pushViewController(lessonViewController, animated: true)

    }

课程视图控制器:

import Foundation
import ReactiveCocoa

class LessonViewController: UITableViewController {

@IBOutlet var lessonNameLabel: UILabel!

private var viewModel: LessonViewModel

init(WithViewModel viewModel: LessonViewModel){
    self.viewModel = viewModel
    super.init(nibName: nil, bundle: nil)
}

required init(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

override func viewDidLoad() {
    super.viewDidLoad()
    bindData()
}

func bindData() {
    // null here!
    if (lessonNameLabel != nil) {
        lessonNameLabel.rac_text <~ viewModel.name
    }
}
}

我怎样才能解决这个问题?

我见过的其他示例代码在 segue 中执行导航,最终调用 init(coder aDecoder: NSCoder) 构造函数,并且所有出口都已初始化。

4

1 回答 1

1

因为您使用初始化程序初始化视图控制器WithViewModel,所以它对故事板一无所知,因此插座没有连接。要按照情节提要中指定的方式连接出口,您需要使用 segue,或者使用情节提要的instantiateViewControllerWithIdentifier(identifier:)方法来创建视图控制器。无论哪种方式,您都不能(轻松)将 ViewModel 作为初始化参数传递,因此您需要公开 viewModel var(删除)并在您的方法private中单独设置它。showLessonView要使用instantiateViewControllerWithIdentifier(identifier:),请在情节提要中给您Lesson View Controller一个标识符(例如“LessonViewController”)。然后修改你showLessonView的如下:

func showLessonView(lessonVM: LessonViewModel) {
    let lessonViewController = self.storyboard!.instantiateViewControllerWithIdentifier(identifier:"LessonViewController") as! LessonViewController
    lessonViewController.viewModel = lessonVM
    self.navigationController?.pushViewController(lessonViewController, animated: true)
}

当从故事板实例化视图控制器时,将init(coder:)使用初始化程序,因此要么删除该方法的覆盖,要么修改它以调用超级实现:

required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}
于 2015-07-06T20:33:50.403 回答