【问题标题】:Dynamic tableview cell, prevent auto height constraint from being created动态表格视图单元格,防止创建自动高度约束
【发布时间】:2017-04-18 01:48:11
【问题描述】:

我已经遇到这个问题几天了,但仍然没有找到解决方法。基本上我正在尝试创建一个带有自定尺寸单元的UITableView。我已经使用UITableViewAutomaticDimension 将单元格的高度设置为自动。单元格有一个高度约束来测试我的代码,因为这个约束应该确定单元格的高度。这是我对单元格的限制:

let views = ["view": view]
self.addConstraints(NSLayoutConstraint.constraints(
    withVisualFormat: "H:|[view]|",
    options: [],
    metrics: nil,
    views: views
))

self.addConstraints(NSLayoutConstraint.constraints(
    withVisualFormat: "V:|[view]|",
    options: [],
    metrics: nil,
    views: views
))

NSLayoutConstraint(item: contentView, attribute: .width, relatedBy: .equal, toItem: self.superview!, attribute: .width, multiplier: 1, constant: 0).isActive = true

这是我收到的错误消息:

2017-04-17 22:40:01.596805-0300 ViraVira-Info[52208:1001696] [LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want. 
    Try this: 
        (1) look at each constraint and try to figure out which you don't expect; 
        (2) find the code that added the unwanted constraint or constraints and fix it. 
    (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) 
(
    "<NSAutoresizingMaskLayoutConstraint:0x600000099190 h=--& v=--& UITableViewCellContentView:0x7f987070f5f0.height == 44.5   (active)>",
    "<NSLayoutConstraint:0x6000000966c0 UIView:0x7f9870709be0.height == 100   (active)>",
    "<NSLayoutConstraint:0x600000098dd0 V:|-(0)-[UIView:0x7f9870709be0]   (active, names: '|':UITableViewCellContentView:0x7f987070f5f0 )>",
    "<NSLayoutConstraint:0x600000098e70 V:[UIView:0x7f9870709be0]-(0)-|   (active, names: '|':UITableViewCellContentView:0x7f987070f5f0 )>"
)

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x6000000966c0 UIView:0x7f9870709be0.height == 100   (active)>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.

如您所见,tableview 会自动创建一个 height constraint,这与我的其他高度限制冲突。

"<NSAutoresizingMaskLayoutConstraint:0x600000099190 h=--& v=--& UITableViewCellContentView:0x7f987070f5f0.height == 44.5   (active)>"

但我找不到删除或阻止此约束发生的方法。我已经尝试将内容视图的translatesAutoresizingMask 设置为false,将单元格视图设置为自身以及将UIView 添加到内容视图中,但没有成功。这样做给了我以下错误:

Warning once only: Detected a case where constraints ambiguously suggest a height of zero for a `tableview cell's` content view. We're considering the collapse unintentional and using standard height instead.

请询问任何其他信息,我很乐意将其添加到此问题中。

【问题讨论】:

  • view.translatesAutoresizingMaskIntoConstraints = false 应该有助于@J.Paravicini
  • 你红了这个问题吗?我说我已经尝试过了,但没有成功:/
  • 在 cell.contentView.translatesAutoresizingMaskIntoConstraints 上试试
  • @J.Paravicini 如果设置所有 view.translatesAutoresizingMaskIntoConstraints = false 则还有其他视图
  • @NazmulHasan 我尝试将所有视图和子视图中的 translatesAutoresizingMaskIntoConstraints 设置为关闭,但在控制台中出现以下错误:仅警告一次:检测到约束模糊地建议高度为零的情况tableview 单元格的内容视图。我们正在考虑意外折叠并改用标准高度。

标签: ios swift uitableview dynamic constraints


【解决方案1】:

这就是你需要做的——:

MARK-:但我是以编程方式完成的。这很完美。

import UIKit

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

   lazy var tableView : UITableView = {
        var tableView  =  UITableView()
        tableView.delegate = self // Table view delegate
        tableView.dataSource = self // table view datasource
        tableView.translatesAutoresizingMaskIntoConstraints = false // set  translatesAutoresizingMaskIntoConstraints to false
        return tableView 
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(tableView) // Add table on view
        tableView.estimatedRowHeight = 50 // table row estimated row height
        tableView.rowHeight = UITableViewAutomaticDimension //Automatic dimensions

        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell") // register cell
        view.addConstraintsWithFormat(format: "H:|[v0]|", views: tableView) // give table view constraints horizontal
        view.addConstraintsWithFormat(format: "V:|[v0]|", views: tableView) // vertical

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    // MARK-: Table view DELEGATE METHODS

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


    // Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
    // Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)


    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = "abcd"
        cell.textLabel?.numberOfLines = 0 // SET YOUR LABEL numberOfLines to 0
        cell.textLabel?.sizeToFit()
        if indexPath.row == 1
        {
            cell.textLabel?.text = "asdvhvcjkhsvcjhsvcjhsvchjvcjhsvcjhsvchdveiuvcjsdvccjgdcgygdchjsvcjsvcjvclsvccvsjvhjsvchsvcvhdchvsjvhcjjhhyuioplkjhxxzasdfghtyuiklopl"
        }
        return cell
    }


     func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
     {
        return UITableViewAutomaticDimension
     }


}
extension UIView
{

    func addConstraintsWithFormat(format:String,views:UIView...)
    {
        var allViews = [String:UIView]()
        for data in 0...views.count-1
        {
            let key = "v\(data)"
            allViews[key] = views[data]
        }
        addConstraints(NSLayoutConstraint.constraints(withVisualFormat: format, options: NSLayoutFormatOptions(), metrics: nil, views: allViews))

    }



}

要使用情节提要,请执行以下操作-:

编码部分-:

ViewController-:

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

    @IBOutlet weak var dynamicTable: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        dynamicTable.estimatedRowHeight = 70 // table row estimated row height
       dynamicTable.rowHeight = UITableViewAutomaticDimension //Automatic dimensions

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    // MARK-: Table view DELEGATE METHODS

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


    // Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
    // Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)


    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! testing
        cell.automaticLabel?.text = "abcd"
        cell.automaticLabel?.numberOfLines = 0 // SET YOUR LABEL numberOfLines to 0
        cell.automaticLabel?.sizeToFit()
        if indexPath.row == 1
        {
            cell.automaticLabel?.text = "asdvhvcjkhsvcjhsvcjhsvchjvcjhsvcjhsvchdveiuvcjsdvccjgdcgygdchjsvcjsvcjvclsvccvsjvhjsvchsvcvhdchvsjvhcjjhhyuioplkjhxxzasdfghtyuiklopl"
        }
        return cell
    }


     func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
     {
        return UITableViewAutomaticDimension
     }

自定义单元格类-:

import UIKit

class testing: UITableViewCell {

    @IBOutlet weak var automaticLabel: UILabel!
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

【讨论】:

  • 只有代码的答案不是很有帮助。请解释为什么这是需要做的。这段代码是如何解决问题中的问题的?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-20
  • 2013-05-16
  • 2014-06-18
  • 1970-01-01
  • 1970-01-01
  • 2015-04-16
  • 1970-01-01
相关资源
最近更新 更多