2016-09-15 34 views
3

我創建了一個帶有xib文件的自定義UITableViewCell。在那裏我已經放置了幾個標籤和相對於contentView寬度的視圖。不幸的是,contentView.bounds.width屬性始終保持不變,無論選擇哪個設備。來自XIB的自定義UITableViewCell:contentView寬度始終相同

我的視圖控制器也從筆尖加載:

class ViewController: UIViewController { 
    @IBOutlet var tableView: UITableView! 

    init(title: String) { 
     super.init(nibName: "ViewController", bundle: nil) 
    } 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     tableView.registerNib(UINib(nibName: "CustomTableViewCell", bundle: nil), forCellReuseIdentifier: "CustomTableViewCell") 
    }  

    func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
     return 1 
    } 

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return 2 
    } 

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCellWithIdentifier("CustomTableViewCell", forIndexPath: indexPath) as! CustomTableViewCell 

     return cell 
    } 

} 

CustomTableViewCell I類打印出來的內容視圖的width屬性:

override func awakeFromNib() { 
     super.awakeFromNib() 

     print("self.contentView.bounds.width: \(self.contentView.bounds.width)") 
    } 

這始終打印出來的寬度設定Interface Builder,儘管它應該遵循使用AutoLayout的tableView的寬度:

enter image description here

嘗試設置單元格的幀之前返回沒有工作:

cell.frame = CGRectMake(0, 0, self.tableView.frame.size.width, 71) 

回答

1

如果你正在使用autolayout那麼你widthcellforrowAtindexpath數,你會得到適當的寬度。 awakeFromNib在您的單元格獲得自動佈局之前被調用,因此它的寬度與interface builder中設置的寬度相同。

第二件事,如果你使用自動佈局然後設置frame沒有意義。如果你想改變height or width那麼你應該採取outlet of your constraint (height or width),你可以改變它的constant到期望值!

如果你想改變高度只有那麼你可以玩heightForRowAtIndexPathif else哪些返回慾望高度根據條件!

+0

謝謝,不知道那些。但是,通過計算'cellForRowAtIndexPath'中的寬度是什麼意思?爲什麼'UITableViewCell'不會自動獲得'tableView'的寬度? – MJQZ1347

+0

'UITableViewCell'根據你的約束獲取寬度,但在調用awakeFromNib之後。所以在'awakeFromNib'你不會得到正確的框架! – Lion