2014-10-17 90 views
2

我正在使用故事板创建自定义单元格。我在故事板连接该单元格,我的tableview:如何在swift中为故事板使用自定义的uitableviewcell

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和初始化函数看起来像这些:

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空白。我究竟做错了什么?

+0

您是否已将'titleLabel'与Interface Builder中的等效标签连接起来? – abinop 2014-10-17 21:48:23

+0

我去分裂助理视图与故事板和单元格视图显示。我从我的标签拖到创建连接的单元格。 – Atma 2014-10-17 21:51:12

+0

空白你的意思是它没有行?你有没有在桌面视图上重载数据? – abinop 2014-10-17 21:59:44

回答

4

我们阵列上工作之前,让我们的基本单元工作:

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 
} 

然后,我们可以帮助您与您的数组,如果字符串。

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

+0

您不应该为故事板中制作的单元格注册一个笔尖。 – rdelmar 2014-10-17 22:58:38

+0

对不起,我确实在这里推荐一个Xib文件。 – 2014-10-17 23:01:38

+0

谢谢,这对我有用;) – 2015-04-07 08:58:40

相关问题