2016-09-02 4 views
2

я создаю простую таблицу, но без раскадровки, просто кодирование, в настоящее время я могу создать таблицу, но когда я добавить ячейку он выходит из строя, это мой переменные:UITableViewCell не показывает

var optionsTableView:UITableView! 
var options = ["Option1", "Option2"] 

Когда Я постучала кнопку появляется таблица, функция:

@IBAction func Options(sender: AnyObject) { 
    if optionsTableView != nil { 
     optionsTableView.removeFromSuperview() 
     self.optionsTableView = nil 
     return 
    } 

    self.optionsTableView = UITableView() 
    self.optionsTableView.backgroundColor = UIColor(white: 0, alpha: 0.95) 
    self.optionsTableView.delegate = self 
    self.optionsTableView.dataSource = self 
    self.optionsTableView.translatesAutoresizingMaskIntoConstraints = false 

    var constraints = [NSLayoutConstraint]() 
    constraints.append(NSLayoutConstraint(item: optionsTableView, attribute: .Leading, relatedBy: .Equal, toItem: self.view, attribute: .Leading, multiplier: 1.0, constant: 100.0)) 
    constraints.append(NSLayoutConstraint(item: optionsTableView, attribute: .Trailing, relatedBy: .Equal, toItem: sender, attribute: .Trailing, multiplier: 1.0, constant: 0)) 
    constraints.append(NSLayoutConstraint(item: optionsTableView, attribute: .Top, relatedBy: .Equal, toItem: sender, attribute: .Bottom, multiplier: 1.0, constant: 5.0)) 

    self.view.addSubview(optionsTableView) 
    self.view.addConstraints(constraints) 

    optionsTableView.addConstraints([NSLayoutConstraint(item: optionsTableView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .Height, multiplier: 1.0, constant: 220.0)]) 
} 

функции для таблицы:

func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
    return 1 
} 

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return self.options.count 
} 

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { 
    return 44.0 
} 

Up чтобы здесь все идет хорошо, но с cellForRowAtIndexPath в приложении падает:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    var cell = optionsTableView.dequeueReusableCellWithIdentifier("cell")! 
    if tableView == optionsTableView { 
     cell = UITableViewCell(style: .Default, reuseIdentifier: "cell") 
     cell.backgroundView = nil 
     cell.backgroundColor = UIColor.clearColor() 
     cell.textLabel?.textColor = UIColor.whiteColor() 
     cell.textLabel?.text = self.options[indexPath.row] 
     return cell 
    } 
    return cell 
} 

В частности, в этой линии авария приложения:

var cell = optionsTableView.dequeueReusableCellWithIdentifier("cell")! 

И консольное говорит: «Фатальная ошибка: неожиданно нашел ноль в то время как разворачивание Факультативного значение ", что вы думаете, что происходит?

+0

У вас есть ячейка с идентификатором повторного использования "cell"? – WMios

ответ

5

Эта строка сбойна, потому что она не находит ячейку с этим идентификатором повторного использования.

Вы должны зарегистрировать его:

self.tableView.registerClass(Cell.self as AnyClass, forCellReuseIdentifier: "cell") 

Таким образом, когда вы вынуждаете разворачивать это не приведет к краху.

+0

О, спасибо! @WMios это работает !!, в настоящее время я не могу голосовать, но поверьте мне, я очень благодарен вам –

+0

@ JulioCesarAguilarJiménez, рад, что смог помочь! – WMios

1

Я немного изменил ваш код. Исправлены ограничения.

import UIKit 

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { 

var optionsTableView = UITableView() 
var options = ["Option1", "Option2"] 

override func viewDidLoad() { 
    super.viewDidLoad() 
    // Do any additional setup after loading the view, typically from a nib. 

    optionsTableView = UITableView(frame: UIScreen.mainScreen().bounds) 
    //optionsTableView.backgroundColor = UIColor(white: 0, alpha: 0.95) 
    optionsTableView.delegate = self 
    optionsTableView.dataSource = self 
    optionsTableView.translatesAutoresizingMaskIntoConstraints = false 

    view.addSubview(optionsTableView) 
    optionsTableView.registerClass(UITableViewCell.classForCoder(), forCellReuseIdentifier: "cell") 

} 

override func viewWillLayoutSubviews() { 

    var constraints = [NSLayoutConstraint]() 
    constraints.append(NSLayoutConstraint(item: optionsTableView, attribute: .Top, relatedBy: .Equal, toItem: topLayoutGuide, attribute: .Bottom, multiplier: 1.0, constant: 0)) 
    constraints.append(NSLayoutConstraint(item: optionsTableView, attribute: .Bottom, relatedBy: .Equal, toItem: bottomLayoutGuide, attribute: .Top, multiplier: 1.0, constant: 0)) 
    constraints.append(NSLayoutConstraint(item: view, attribute: .Trailing, relatedBy: .Equal, toItem: optionsTableView, attribute: .Trailing, multiplier: 1.0, constant: 0)) 
    constraints.append(NSLayoutConstraint(item: optionsTableView, attribute: .Leading, relatedBy: .Equal, toItem: view, attribute: .Leading, multiplier: 1.0, constant: 0)) 

    view.addConstraints(constraints) 
} 


func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
    return 1 
} 

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return self.options.count 
} 

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { 
    return 44.0 
} 

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 

    let cell = optionsTableView.dequeueReusableCellWithIdentifier("cell")! 
    cell.textLabel?.text = options[indexPath.row] 
    return cell 

} 
}