如何在swift中使用自定义的uitableviewcell作为故事板

时间:2014-10-17 21:40:12

标签: ios iphone uitableview swift

我正在使用故事板来创建自定义单元格。我已将这个单元格连接到故事板中的tableview:

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
    }

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

1 个答案:

答案 0 :(得分:5)

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

class NewsCell: UITableViewCell {

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

}
表类中的

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
}

然后,如果是字符串,我们可以帮助您使用数组。

如果在故事板中,您可以忘记注册nib代码。但值得学习如何做。