2016-09-15 2 views
3

私はxibファイルでカスタムUITableViewCellを作成しました。そこには、contentViewの幅に関連して、いくつかのラベルとビューが配置されています。残念ながら、contentView.bounds.widthプロパティは、どのデバイスが選択されても同じままです。これは、常にで設定した幅をプリントアウトXIBからのカスタムUITableViewCell:contentViewの幅は常に同じ

override func awakeFromNib() { 
     super.awakeFromNib() 

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

:私はコンテンツビューのwidthプロパティをプリントアウトCustomTableViewCellクラスで

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 
    } 

} 

私のViewControllerもペン先からロードされますAutoLayoutを使用するtableViewの幅に準拠する必要があるにもかかわらず、Interface Builder:

返す前に、セルの枠を設定しようとすると、10

は動作しませんでした:

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

答えて

1

をおautolayoutを使用している場合は、cellforrowAtindexpathでごwidthを数えると、あなたは適切な幅を取得します。 awakeFromNibは、セルが自動レイアウトを取得する前に呼び出され、interface builderに設定されたのと同じ幅を与えます。

自動レイアウトを使用している場合、次にframeを設定することは意味を持ちません。 height or widthを変更する場合は、outlet of your constraint (height or width)とし、constantを希望の値に変更することができます。

高さを変更したい場合は、とif elseで再生して、条件ごとの希望の高さを返します!

+0

ありがとうございました。それらについては知りませんでした。しかし、 'cellForRowAtIndexPath'の幅を数えることはどういう意味ですか?なぜ 'UITableViewCell'は自動的に' tableView'の幅を持っていませんか? – MJQZ1347

+0

'UITableViewCell'はあなたの制約に従って幅を取得しますが、' awakeFromNib'が呼び出された後に幅を取得します。だから 'awakeFromNib'では正しいフレームを取得できません! – Lion

関連する問題