2014-09-23 108 views
7

因此,我創建了一個自定義表格視圖單元格,左側有一個標籤,右側有一個UIImageView。 標籤有100和UIImageView的一個標籤110在xcode 6中使用swift自定義表格視圖單元

我的代碼標籤如下:

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

    var cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier("ThemeCell") as UITableViewCell 

    let theme = themes[indexPath.row] 

    var themeName = cell.viewWithTag(100) as? UILabel 
    themeName?.text = theme.themeName 

    let themeImage = cell.viewWithTag(110) as? UIImageView 
    themeImage?.image = UIImage(named: "test.png") 

    //1 
    //cell.imageView?.image = UIImage(named: "test.png") 

    println("The loaded image: \(themeImage?.image)") 

    return cell; 
} 

按原樣,則顯示THEMENAME但themeImage沒有出現,儘管從println似乎是加載圖像。如果我取消註釋1中的代碼,圖像將顯示在自定義單元格中,但當然不會顯示在正確的位置,因爲它未添加到我在IB中創建的UIImageView。 任何想法我可能做錯了什麼?標籤都是正確的。 謝謝

+0

我在IB中有一個自定義單元,以便能夠添加UIImageView,但我沒有創建一個擴展UITableViewCell的MyCustomCell類。我不認爲我需要。我只需要有一個UILabel和UIImageView。 – 2014-09-23 16:21:56

+0

添加以下代碼以查看是否可以顯示'UIImageView':themeImage?.backgroundColor = UIColor.greenColor()'。 – 2014-09-23 16:35:22

+0

http://stackoverflow.com/questions/24170922/creating-custom-tableview-cells-in-swift/38470749#38470749 – 2016-07-20 01:25:08

回答

12

首先,您需要使用自動佈局機制固定視圖。打開界面生成器,您的自定義單元格內的標籤上點擊左鍵,然後例如執行下列操作:

  1. 編輯 - >釘 - >寬度
  2. 編輯 - >釘 - >高度
  3. 編輯 - >引腳 - >前導空格,以上海華
  4. 編輯 - >釘 - >頂層空間,以上海華

圖像相同的自定義單元格內

  1. 編輯器 - >釘 - >寬度
  2. 編輯 - >釘 - >高度
  3. 編輯 - >釘 - >尾部的空格,以上海華
  4. 編輯 - >釘 - >頂層空間,以上海華

然後爲您的單元格創建自定義類。例如

MyCustomCell.swift

import Foundation 
import UIKit 

class MyCustomCell: UITableViewCell { 
    @IBOutlet weak var myLabel: UILabel! 
    @IBOutlet weak var myImageView: UIImageView! 
} 

然後設置自定義類的細胞,並創建元素的連接。

現在在tableViewController您可以設置值的元素,而標籤:

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

    var cell: MyCustomCell = tableView.dequeueReusableCellWithIdentifier("ThemeCell") as MyCustomCell 

    let theme = themes[indexPath.row] 

    cell.myLabel.text = theme.themeName 
    cell.myImageView.image = UIImage(named: "test.png") 

    println("The loaded image: \(cell.myImageView.image)") 

    return cell; 
} 
3

好了,該故障是不是在UITable所有,但一個事實,即自動版式設置不正確,並該圖像出現在桌面外...

相關問題