【问题标题】:Custom table view cell with swift in xcode 6在 xcode 6 中使用 swift 自定义表格视图单元格
【发布时间】:2014-11-17 22:26:19
【问题描述】:

所以,我创建了一个自定义表格视图单元格,左侧有一个标签,右侧有一个 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 中。 有什么想法我可能做错了吗?标签都是正确的。 谢谢

【问题讨论】:

  • 我在 IB 中有一个自定义单元格,以便能够添加 UIImageView,但我还没有创建扩展 UITableViewCell 的 MyCustomCell 类。我不认为我需要。我只需要一个 UILabel 和 UIImageView。
  • 添加如下代码,看看你的UIImageView能不能显示:themeImage?.backgroundColor = UIColor.greenColor()

标签: ios xcode uitableview swift uiimageview


【解决方案1】:

首先,您需要使用自动布局机制固定您的视图。打开界面生成器,左键单击自定义单元格内的标签,然后执行以下操作:

  1. 编辑器->引脚->宽度
  2. 编辑器->引脚->高度
  3. Editor->Pin->Leading Space to Superview
  4. Editor->Pin->Top Space to Superview

自定义单元格中的图像也是如此

  1. 编辑器->引脚->宽度
  2. 编辑器->引脚->高度
  3. Editor->Pin->Trailing Space to Superview
  4. Editor->Pin->Top Space to Superview

然后为您的单元格创建自定义类。例如

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;
}

【讨论】:

    【解决方案2】:

    好的,所以问题根本不在 UITable 中,而是在 AutoLayout 设置不正确并且图像出现在 tableview 之外的事实......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-09
      • 2014-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多