不理解为什么我的属性重置为指定的原始值(0.1)。我从外部方法传入0.5的fillHeight。该属性在easy 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
编辑: 外部调用来自UITableViewController,带有自定义UITableViewCell。图像是针对细胞的。
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
}
}
答案 0 :(得分:1)
问题是您在配置单元时分配新的MyView
实例。您不必这样做,因为视图已经存在(因为您在nib中添加了它)。
所以只需在单元格的fillHeight
上设置myView
即可。这解决了问题:
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!)
....
}