2015-10-10 54 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

相關問題