[英]Custom table view cell with swift in xcode 6
因此,我創建了一個自定義表格視圖單元格,左側是標簽,右側是UIImageView。 標簽的標簽為100,UIImageView的標簽為110。
我的代碼如下:
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中。 我有什么想法可能做錯了嗎? 標簽都是正確的。 謝謝
首先,您需要使用自動布局機制固定視圖。 打開界面構建器,左鍵單擊自定義單元格內的標簽,然后執行以下操作:
自定義單元格中的圖像也是如此
然后為您的單元格創建自定義類。 例如
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;
}
好的,所以故障根本不在UITable中,而是因為AutoLayout沒有正確設置而且圖像出現在tableview之外...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.