2015-10-10 55 views
0

不理解为什么我的属性重置为分配的原始值(0.1)。我从外部方法中传入0.5的fillHeight。该属性在便捷初始化中设置,但不会传递到drawRect。我错过了什么?将属性传递到UIView中的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

EDIT : 外部调用来自具有自定义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 
    } 

}

+0

我试图重现你的错误,但在我的情况下,它打印'drawRect self.fillHeight:0.5'。你可以在代码初始化视图并将其添加到视图堆栈吗? – joern

+0

谢谢你的joern。我已经添加了电话号码 – Kurt

+0

请问您如何在您的自定义单元格中定义'myView'属性?它是一个可选属性? – joern

回答

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!) 
    .... 
} 
+0

非常感谢你的支持! – Kurt

相关问题