【问题标题】:Having trouble passing property into drawRect in UIView在 UIView 中将属性传递给 drawRect 时遇到问题
【发布时间】:2015-10-10 20:25:44
【问题描述】:

不明白为什么我的属性会重置为分配的原始值 (0.1)。我从外部方法传入 0.5 的填充高度。该属性在便利初始化中设置,但不会延续到 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
    }

}

【问题讨论】:

  • 我试图重现您的错误,但在我的情况下它打印drawRect self.fillHeight: 0.5。您可以发布初始化视图并将其添加到视图堆栈的代码吗?
  • 谢谢乔恩。我已添加通话
  • 能否请您发布您如何在自定义单元格中定义myView 属性?它是可选属性吗?
  • MyView 是我上面列出的类,而不是 func configureCell 上的属性。调用是通过方便的 init 进行的。 'Cell' 不是可选的,因为它是函数 configureCell 的属性。 'myObject.fillAmount' 是可选的,如输出控制台中所述
  • 但是如果你在做cell.myView = ...myView 必须是单元格的属性。因为UITableViewCell 没有该名称的属性。

标签: ios uiview swift2 drawrect


【解决方案1】:

问题是您在配置单元时分配一个新的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!)
    ....
}

【讨论】:

  • 非常感谢您对我的支持!
猜你喜欢
  • 2013-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-05
相关资源
最近更新 更多