Swift 4 UITableView单元格高度不起作用

时间:2017-09-25 16:38:56

标签: ios swift uitableview swift4

我试图在Xcode9上设置高度,但它似乎无法正常工作。我可以使用76的固定大小。我有一个Image,我想要10个填充,高度为56.

我尝试过的事情: 1.在尺寸检查器中设置它 2.通过编码,但它不起作用

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.rowHeight = UITableViewAutomaticDimension
    self.tableView.estimatedRowHeight = 76
    getArticles() // returns json data
}

和tableView

    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: "ArticleCell") as? ArticleCell else { return UITableViewCell() }

    cell.titleLabel.text = articles[indexPath.row].title

    if let imageURL = URL(string: articles[indexPath.row].image) {
        DispatchQueue.global().async {
            let data = try? Data(contentsOf: imageURL)
            if let data = data {
                let image = UIImage(data: data)
                DispatchQueue.main.async {
                    cell.imgView.image = image
                }
            }
        }
    }

    cell.contentView.setNeedsLayout()
    cell.contentView.layoutIfNeeded()

    return (cell)
}

似乎没什么用,它保持在同一高度。我曾经尝试过,有没有约束。

我在这里做错了什么?

修改 我已经从Prototype单元格更改为Xib格式。现在我有它工作,除了我得到约束错误。

The constraints setup 这是它工作的唯一方式。如果我移除底部边距,它会再次回到较小的尺寸。如果删除图像高度,则相同。

    2017-09-25 19:26:37.842902+0200 Proj010916-NL_nl[56361:915542] [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. 
(
    "<NSLayoutConstraint:0x60c000093c90 UIImageView:0x7fec2800cd60.height == 56   (active)>",
    "<NSLayoutConstraint:0x60c000093ce0 UIImageView:0x7fec2800cd60.top == UITableViewCellContentView:0x7fec2800aa70.topMargin + 10   (active)>",
    "<NSLayoutConstraint:0x60c000093d80 UITableViewCellContentView:0x7fec2800aa70.bottomMargin == UIImageView:0x7fec2800cd60.bottom + 10   (active)>",
    "<NSLayoutConstraint:0x604000097160 'UIView-Encapsulated-Layout-Height' UITableViewCellContentView:0x7fec2800aa70.height == 92   (active)>"
)

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x60c000093c90 UIImageView:0x7fec2800cd60.height == 56   (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.

接下来的任务是重做segue,因为它现在是vc而不是内部的单元格。

1 个答案:

答案 0 :(得分:2)

您是否尝试过实现heightForRowAtIndexPath委托方法?

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

这样,您可以在UITableView中为每个indexPath设置不同的高度。