【问题标题】:how to use a custom uitableviewcell for storyboards in swift如何在 swift 中为故事板使用自定义的 uitableviewcell
【发布时间】:2014-10-17 21:40:12
【问题描述】:

我正在使用情节提要创建自定义单元格。我已将此单元格连接到情节提要中的表格视图:

import UIKit

class NewsCell: UITableViewCell {

    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var summaryLabel: UILabel!



    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

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

        // Configure the view for the selected state
    }

}

我的 cellforrowatindexpath 和 init 函数如下所示:

var newsItems:[NewsItem]

required init(coder aDecoder:NSCoder){
    newsItems = [NewsItem]()

    let item1 = NewsItem()
    item1.title = "I am so awesome"
    item1.summary = "My awesome summary."

    newsItems.append(item1)

    super.init(coder: aDecoder)
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cellIdentifier = "NewsCell"
        var cell: NewsCell! = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? NewsCell

        if cell == nil {
            cell = NewsCell()
        }

        let item = newsItems[indexPath.row]

        if let titleLabel = cell.titleLabel{
            titleLabel.text = item.title
        }

        return cell
    }

当我这样做时,我的单元格在我的表格视图中显示为空白。我做错了什么?

【问题讨论】:

  • 您是否将 titleLabel 与 Interface Builder 中的等效标签连接?
  • 我进入了拆分助手视图,其中显示了情节提要和单元格视图。我从标签拖到创建连接的单元格。
  • 空白是指没有行吗?你在 table view 上做了 reloadData 吗?
  • 您是否将原型单元的类(在故事板中)设置为NewsCell
  • 你是否实现了 numberOfRowsInSection:,并从中返回了一个非零数?

标签: ios iphone uitableview swift


【解决方案1】:

在我们处理您的阵列之前,让我们让基本单元工作:

class NewsCell: UITableViewCell {

    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var summaryLabel: UILabel!

}

在您的 Table 类中:

override func viewDidLoad() {
        super.viewDidLoad()

        self.tableView.registerNib(UINib(nibName: "NewsCell", bundle: nil)!,
            forCellReuseIdentifier: "NewsCell")

    let title = "I am so awesome"
    let summary = "My awesome summary."

    }


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

        let cell = tableView.dequeueReusableCellWithIdentifier("NewsCell", forIndexPath: indexPath) as NewsCell


cell.titleLabel = title
cell.SummaryLabel = summary

return cell
}

那么我们可以帮助您处理数组 if 字符串。

如果在情节提要中,您可以忘记注册笔尖代码。但值得学习如何去做。

【讨论】:

  • 您不应该为情节提要中制作的单元格注册笔尖。
  • 对不起,我这里确实推荐一个xib文件。
猜你喜欢
  • 1970-01-01
  • 2015-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-18
  • 1970-01-01
  • 2013-09-14
  • 2016-03-05
相关资源
最近更新 更多