2014-09-23 133 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所有,但一个事实,即自动版式设置不正确,并该图像出现在桌面外...

相关问题