在 cellForRowAtIndexPath 以编程方式传递 UIImageView

Passing UIImageView Programmatically at cellForRowAtIndexPath

我有一个 UITableViewController 并希望在 cellForRowAtIndexPath 传递一个 imageView。

阵列已设置:

func setupArrays (){

    if NSUserDefaults.standardUserDefaults().boolForKey("stepsSwitch") == true {
        titleArray.append(stepsCell.title())
        iconArray.append(iconFunction1.icon())
    }

    if NSUserDefaults.standardUserDefaults().boolForKey("hrSwitch") == true {
        titleArray.append(heartRateCell.title())
        iconArray.append(iconFunction2.icon())
    }

    if NSUserDefaults.standardUserDefaults().boolForKey("weightSwitch") == true {
        titleArray.append(weightCell.title())
        iconArray.append(iconFunction3.icon())
    }
}

我在 cellForRowAtIndexPath

中调用它们
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var myCell:TableViewCell = tableView.dequeueReusableCellWithIdentifier("myCell") as TableViewCell

    myCell.title.text = titleArray[indexPath.row]
    myCell.icon = iconArray[indexPath.row]

    return myCell    }

在 tableViewCell 中我有网点:

import UIKit

class TableViewCell: UITableViewCell {

    @IBOutlet var title: UILabel!
    @IBOutlet var icon: UIImageView!

我在单独的文件中创建标题和图标 imageView。 图标图片查看:

import UIKit

class IconFunction1: UITableViewCell{

    func icon() -> UIImageView {
        var imageName = "HR-white-140px-height.png"
        let image = UIImage(named: imageName)
        let imageView = UIImageView(image: image!)

        imageView.frame = CGRect(x: 282.5, y: 8, width: 25, height: 25)
        self.addSubview(imageView)
        imageView.layer.zPosition = 10

        return imageView
    }

标题:

import Foundation

class StepsCell: CellProtocol {

    func title () -> String{

        return "Steps"

    }

}

在主情节提要中,我添加了一个 UIImageView,其引用出口为 myCell。

问题: 代码运行没有错误,标题加载正确,但是 tableView 没有加载图标。它是不可见的。为什么?

问题:如何在 cellForRowAtIndexPath 传递 ImageView?我做错了什么?

接受的答案没有直接回答我的问题,但我接受了它,因为它解决了问题并解释了为什么我的实现是错误的。

您正在更改图像视图,但它应该是图像

func icon() -> UIImage? {
    var imageName = "HR-white-140px-height.png"
    return UIImage(named: imageName)
}

iconArray.append(iconFunction.icon())
myCell.icon.image = iconArray[indexPath.row]

P.S。您的实施看起来很复杂...

更新: 如果你想改变视图的外观,你应该尽可能多地尝试在 Interface Builder 中做。但是,如果您被迫以编程方式更改外观,则应将视图子类化,例如

class MyCell: UITableViewCell{
    @IBOutlet var title: UILabel!
    @IBOutlet var icon: UIImageView!

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        icon.frame = CGRect(x: 282.5, y: 8, width: 25, height: 25)
        icon.layer.zPosition = 10
        var imageName = "HR-white-140px-height.png"
        icon.image = UIImage(named: imageName)
    }
}