我正在尝试设置主详细信息导航。 我用的是storyboard,master是动态表,details是静态表。 我有一个 nameLabel 设置作为 Controller 中的导出,但是当我尝试在 viewDidLoad 中访问它时,它仍然设置为 nil。
我没有使用 prepareForSegue,而是使用了 didSelectRowAtIndexPath,它像这样推送详细 View :(因为我使用的是 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)
}
类(class) View Controller :
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) 构造函数并且所有导出都已初始化。
最佳答案
因为您使用 WithViewModel
初始化程序初始化 View Controller ,所以它对 Storyboard 一无所知,因此 socket 没有连接。要按照 Storyboard 中指定的方式连接导出,您需要使用 segue,或者使用 Storyboard 的 instantiateViewControllerWithIdentifier(identifier:)
方法来创建 View Controller 。无论哪种方式,您都不能(轻松地)将 ViewModel 作为参数传递给初始化,因此您需要公开 viewModel var(删除 private
)并在 showLessonView 中单独设置它
方法。要使用 instantiateViewControllerWithIdentifier(identifier:)
,请在 Storyboard中为您的 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)
}
当从 Storyboard实例化 View Controller 时,使用 init(coder:)
初始化程序,因此要么删除该方法的覆盖,要么修改它以调用 super 实现:
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
关于ios - 链接到静态 TableView 中的控件的 socket 未初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31250814/