ios – 自定义表格视图单元格,带有swift in xcode 6

前端之家收集整理的这篇文章主要介绍了ios – 自定义表格视图单元格,带有swift in xcode 6前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
因此,我创建了一个自定义表格视图单元格,左侧是标签,右侧是UI ImageView.
标签标签为100,UIImageView的标签为110.

我的代码如下:

  1. override func tableView(tableView: UITableView,cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
  2.  
  3. var cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier("ThemeCell") as UITableViewCell
  4.  
  5. let theme = themes[indexPath.row]
  6.  
  7. var themeName = cell.viewWithTag(100) as? UILabel
  8. themeName?.text = theme.themeName
  9.  
  10. let themeImage = cell.viewWithTag(110) as? UIImageView
  11. themeImage?.image = UIImage(named: "test.png")
  12.  
  13. //1
  14. //cell.imageView?.image = UIImage(named: "test.png")
  15.  
  16. println("The loaded image: \(themeImage?.image)")
  17.  
  18. return cell;
  19. }

按原样,显示themeName但不显示themeImage,尽管从println看起来似乎已加载图像.如果我取消注释1中的代码,图像将出现在自定义单元格中,但当然不会出现在正确的位置,因为它没有添加到我在IB中创建的UIImageView中.
我有什么想法可能做错了吗?标签都是正确的.
谢谢

解决方法

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

>编辑器 – > Pin->宽度
>编辑 – > Pin->高度
>编辑 – > Pin->领先空间到Superview
>编辑 – > Pin-> Topview到Superview

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

>编辑器 – > Pin->宽度
>编辑 – > Pin->高度
>编辑 – > Pin->尾随空间到Superview
>编辑 – > Pin-> Topview到Superview

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

MyCustomCell.swift

  1. import Foundation
  2. import UIKit
  3.  
  4. class MyCustomCell: UITableViewCell {
  5. @IBOutlet weak var myLabel: UILabel!
  6. @IBOutlet weak var myImageView: UIImageView!
  7. }

然后为您的单元格设置自定义类,并从元素创建连接.

现在在tableViewController中,您可以在没有标签的情况下为元素设置值:

  1. override func tableView(tableView: UITableView,cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
  2.  
  3. var cell: MyCustomCell = tableView.dequeueReusableCellWithIdentifier("ThemeCell") as MyCustomCell
  4.  
  5. let theme = themes[indexPath.row]
  6.  
  7. cell.myLabel.text = theme.themeName
  8. cell.myImageView.image = UIImage(named: "test.png")
  9.  
  10. println("The loaded image: \(cell.myImageView.image)")
  11.  
  12. return cell;
  13. }

猜你在找的iOS相关文章