无法将 属性 传递到 UIView 中的 drawRect

Having trouble passing property into drawRect in UIView

不明白为什么我的 属性 重置为原始分配值 (0.1)。我从外部方法传入 0.5 的 fillHeight。 属性 在 convenience init 中设置,但不会转移到 drawRect。我错过了什么?

import UIKit

class MyView: UIView {

  var fillHeight: CGFloat = 0.1

  override init(frame: CGRect) {
    super.init(frame: frame)

  }
  convenience init(fillHeight: CGFloat) {

    self.init()
    self.fillHeight = fillHeight
    print("self.fillHeight: \(self.fillHeight) and fillHeight: \(fillHeight)")

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

  }

  override func drawRect(rect: CGRect) {

    print("drawRect self.fillHeight: \(self.fillHeight)")
    // custom stuff
  }

}

控制台输出:

outsideAmount:可选(0.5)

self.fillHeight: 0.5 和 fillHeight: 0.5

drawRect self.fillHeight: 0.1

编辑: 外部调用来自带有自定义 UITableViewCell 的 UITableViewController。该图像用于单元格。

func configureCell(cell: CustomTableViewCell, atIndexPath indexPath: NSIndexPath) {

    let myObject = self.fetchedResultsController.objectAtIndexPath(indexPath) as! MyObject

    cell.nameLabel.text = myObject.name
    cell.strengthLabel.text = myObject.strength

    cell.myView = MyView(fillHeight: CGFloat(myObject.fillAmount!))
    ...

更多编辑:

import UIKit

class CustomTableViewCell: UITableViewCell {

  @IBOutlet weak var nameLabel: UILabel!
  @IBOutlet weak var strengthLabel: UILabel!
  @IBOutlet weak var myView: MyView!


    override func awakeFromNib() {
        super.awakeFromNib()

    }

    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

问题是每次配置单元时都会分配一个新的 MyView 实例。您不必这样做,因为视图已经存在(因为您已将其添加到笔尖中)。

因此只需在单元格的 myView 上设置 fillHeight。这解决了问题:

func configureCell(cell: CustomTableViewCell, atIndexPath indexPath: NSIndexPath) {
    let myObject = self.fetchedResultsController.objectAtIndexPath(indexPath) as! MyObject
    cell.nameLabel.text = myObject.name
    cell.strengthLabel.text = myObject.strength
    cell.myView.fillHeight = CGFloat(myObject.fillAmount!)
    ....
}