1

当我加载我的应用程序时,会发生这种情况。由于某种原因,表格视图加载为空白。只有当我选择单元格并单击另一个单元格时,才会显示先前选择的单元格。但是对于第一个单元格,无论我在哪里/如何单击,我仍然看不到第一个单元格。

我不明白为什么会发生这种情况,因为我遵循了本教程。显然我做错了什么,如果有人能告诉我为什么会发生这种情况以及如何解决它,我将不胜感激。

在主情节提要中,我使用 atableViewController SummaryTableViewController和 custom UITableViewCell DayOfWeekTableViewCell。我有一个用于表格视图单元格的 nib 文件,名为DayofWeekSpendingTableViewCell.xib. 这是我所有文件及其文件名的列表。

这是我的SummaryTableViewController代码:

class SummaryTableViewController: UITableViewController {
    var dayOfWeek: [String] = [String]()
    var totalSpentPerDay: [Double] = [Double]()

    override func viewDidLoad() {
        super.viewDidLoad()

        dayOfWeek = ["MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"]
        totalSpentPerDay = [0, 7.27, 0, 0, 39, 0, 0]
    }

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

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

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCellWithIdentifier("summaryCell", forIndexPath: indexPath) as! DayOfWeekTableViewCell

        // Configure the cell...
        let nib = NSBundle.mainBundle().loadNibNamed("DayofWeekSpendingTableViewCell", owner: self, options: nil)
        cell = nib[0] as! DayOfWeekTableViewCell

        cell.dayOfWeek.text = dayOfWeek[indexPath.row]
        cell.totalAmountSpent.text = String(totalSpentPerDay[indexPath.row])

        return cell
    }
}

这是我的自定义单元格DayOfWeekTableViewCell代码:

class DayOfWeekTableViewCell: UITableViewCell {

    @IBOutlet weak var dayOfWeek: UILabel!
    @IBOutlet weak var totalAmountSpent: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()
    }

    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
    }

}

在主情节提要中,我...

在笔尖文件DayofWeekSpendingTableViewCell.xib中,我...

4

1 回答 1

4

不是在 cellForRowAtIndexPath 中加载 NIB,而是在 viewDidLoad() 中加载 NIB 并注册它以与表视图一起使用

override func viewDidLoad() {
    super.viewDidLoad()

    dayOfWeek = ["MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"]
    totalSpentPerDay = [0, 7.27, 0, 0, 39, 0, 0]
    // Create a nib for reusing
    let nib = UINib(nibName: "DayofWeekSpendingTableViewCell", bundle: nil)
    tableView.registerNib(nib, forCellReuseIdentifier: "summaryCell")
}

然后您可以直接访问 cellForRowAtIndexPath 中的单元格:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    // Configure the cell...
    let cell = tableView.dequeueReusableCellWithIdentifier("summaryCell", forIndexPath: indexPath) as! DayOfWeekTableViewCell
    cell.dayOfWeek.text = dayOfWeek[indexPath.row]
    cell.totalAmountSpent.text = String(totalSpentPerDay[indexPath.row])

    return cell
}
于 2016-01-07T18:53:46.650 回答