2014-10-17 88 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

相關問題