如何从func viewDidLoad在我的故事板中初始化UILabel?

时间:2015-06-20 20:06:34

标签: ios swift

这里我为testview控制器调用init。我究竟做错了什么?我纠正了几个小时。

class FilmTableViewController: UITableViewController, UISearchBarDelegate, UISearchDisplayDelegate {


@IBOutlet var searchBar: UISearchBar!
@IBOutlet weak var tableViewFilm: UITableView!

var request: Request?
var filmObj: Film?
var arrayFilm = [Film?]()
var imageFilm: UIImage!


override func viewDidLoad() {

    super.viewDidLoad()
    searchBar.delegate = self
    tableViewFilm.delegate = self
    tableViewFilm.tableFooterView = UIView(frame: CGRectZero)
    tableViewFilm.backgroundColor = UIColor(red: 36.0/255, green: 49.0/255, blue: 65.0/255, alpha: 1.0)
    var str = "Hello"
    var str2 = "World"
    TestViewController(film: str, str: str2)


}}

但此时应用程序崩溃了。我不明白为什么。

class TestViewController: UIViewController {

@IBOutlet weak var labelOne: UILabel!

@IBOutlet weak var label2: UILabel!


init(film: String, str: String) { // here film and str not equal nil
    self.labelOne.text = film  // crashes here "found nil"
    self.label2.text = str
    super.init(nibName: nil, bundle: nil)
}

required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

override func viewDidLoad() {
    super.viewDidLoad()

}
}

将init调用到vievdidload可能是不可能的?我在Interface builder中连接了所有IBOutlets。

1 个答案:

答案 0 :(得分:0)

TestViewController更新为

class TestViewController: UIViewController {

    @IBOutlet weak var labelOne: UILabel!

    @IBOutlet weak var label2: UILabel!

    var film: Film?

    override func viewDidLoad() {
        super.viewDidLoad()
        self.labelOne.text = film?.title
    }
}

由于您的故事板中定义了TestViewController,因此您需要按以下方式对其进行初始化:

if let viewC = UIStoryboard(name: "YOUR_STORYBOARD_NAME", bundle: nil).instantiateViewControllerWithIdentifier("ID_OF_TEST_VIEW_CONTROLLER") as? TestViewController {
        // your TestViewController should be correctly initialised now
        // and now you can add the film object to it
        viewC.film = YOUR_MOVIE
}

您需要使用TestViewController的故事板ID而不是ID_OF_TEST_VIEW_CONTROLLER。

通过这种方式,如果您使用segues,您还可以轻松准备TestViewController以进行显示:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if let viewC = segue.destinationViewController as? TestViewController {
        viewC.film = YOUR_MOVIE
    }
}