【发布时间】: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