簡體   English   中英

在表格視圖單元格中添加自動布局約束。

[英]Adding auto layout constraints in a tableview cell.

我試圖將UIImageView添加到單元格並以編程方式添加自動布局約束。 但是,這給了我以下錯誤: The view hierarchy is not prepared for the constraint... When added to a view, the constraint's items must be descendants of that view (or the view itself). This will crash if the constraint needs to be resolved before the view hierarchy is assembled. The view hierarchy is not prepared for the constraint... When added to a view, the constraint's items must be descendants of that view (or the view itself). This will crash if the constraint needs to be resolved before the view hierarchy is assembled. 我查看了以下幾篇文章: Swift,Constraint,未為該約束准備視圖層次結構在這種情況下為什么我的布局約束返回錯誤? (Swift)Swift,Constraint,視圖層次結構沒有為約束准備 我不能添加到這些帖子建議我添加的代碼中的一件事是setTranslatesAutoresizingMaskIntoConstraints 當我嘗試將此功能添加到imageView ,出現錯誤。

這是我的代碼:

    func cellTwo(indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("cellTwo", forIndexPath: indexPath) as! CathyTaskLogTwoTableViewCell

        let imageView:UIImageView = UIImageView(image: UIImage(named: "defaultPicture"))
        imageView.frame.size.width = 100
        imageView.frame.size.height = 31
                let horizonalContraints = NSLayoutConstraint(item: imageView, attribute:
            .LeadingMargin, relatedBy: .Equal, toItem: cell,
            attribute: .LeadingMargin, multiplier: 1.0,
            constant: 20)
        imageView.addConstraint(horizonalContraints)

        cell.addSubview(imageView)

        return cell

    }

提前非常感謝您的幫助:)

  1. 順序為:

    • 實例化子視圖(例如圖像視圖);
    • 設置translatesAutoresizingMaskIntoConstraintsfalse ;
    • 調用addSubview將其添加到視圖層次結構中;
    • 添加約束。
  2. 如果使用約束,則根本不要設置frame 一切都應由約束條件來定義。

  3. 調用dequeueReusableCellWithIdentifier然后添加一個子視圖可能並不明智。 如果該單元被重用怎么辦? 您將多次添加相同的子視圖。 子視圖的編程添加可能最好放在awakeFromNib的單元子類實現中(如果從情節提要或NIB中實現),或者如果以編程方式構建,則將其放入init(style;, reuseIdentifier) 或者,最簡單的是,根本不以編程方式創建單元並使用情節提要或NIB。

在以編程方式將約束添加到任何視圖之前,應將其添加為子視圖,並將translatesAutoresizingMaskIntoConstraints設置為false,然后添加所需的約束。 喜歡

 cell.addSubview(imageView)
 imageView.translatesAutoresizingMaskIntoConstraints = false

 //now add your required constraints

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM