UITableViewAutomaticDimension 不按预期工作.迅速 [英] UITableViewAutomaticDimension works not as expected. Swift

查看:24
本文介绍了UITableViewAutomaticDimension 不按预期工作.迅速的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读 Ray Wenderlich

一些更新!

我已经尝试将以下代码放入 viewDidLoad():

tableView.rowHeight = 44tableView.estimatedRowHeight = UITableViewAutomaticDimension

启用委托方法并禁用它们.结果是一样的:(

解决方案

你做错了很多事情,但主要点是你使用了greaterThanOrEqualTo:.

相反,它应该是:

cellCaption.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -8),

此外,您当前的代码是在每次设置文本时添加一个新标签作为子视图.单元格是重复使用的,因此您只需在创建单元格时添加标签即可.

接下来,表格的正确属性是:

 tableView.rowHeight = UITableViewAutomaticDimensiontableView.estimatedRowHeight = 44

将这两行放在你的table view controller的viewDidLoad()中,并且不要实现heightForRowAtestimatedHeightForRowAt 函数.您可以完全删除您的扩展程序.

最后,您只需要设置一次约束.在 layoutSubviews() 中绝对不是.

这是一个完整的例子:

<代码>////NotesTableViewController.swift////由 Don Mag 于 18 年 8 月 29 日创建.//导入 UIKit类 NotesModel:NSObject {变量名称:字符串 = ""}类 NotesCell:UITableViewCell {懒惰私有 var cellCaption: UILabel = {让标签 = UILabel()label.translatesAutoresizingMaskIntoConstraints = falselabel.font = UIFont.systemFont(ofSize: 20, weight: UIFont.Weight.medium)label.numberOfLines = 0label.lineBreakMode = .byWordWrapping退货标签}()func 配置(注意:NotesModel){cellCaption.text = note.name}覆盖初始化(样式:UITableViewCellStyle,reuseIdentifier:字符串?){super.init(样式:样式,reuseIdentifier:reuseIdentifier)通用初始化()}需要初始化?(编码器aDecoder:NSCoder){super.init(编码器:aDecoder)通用初始化()}func commonInit() ->空白 {contentView.addSubview(cellCaption)NSLayoutConstraint.activate([cellCaption.topAnchor.constraint(equalTo: contentView.topAnchor, 常量: 8),cellCaption.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, 常量: 8),cellCaption.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, 常量: -8),cellCaption.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, 常量: -8),])}}类 NotesTableViewController:UITableViewController {覆盖 func viewDidLoad() {super.viewDidLoad()tableView.rowHeight = UITableViewAutomaticDimensiontableView.estimatedRowHeight = 44}//MARK: - 表视图数据源覆盖 func numberOfSections(in tableView: UITableView) ->整数{返回 1}覆盖 func tableView(_ tableView: UITableView, numberOfRowsInSection 部分: Int) ->整数{返回 8}覆盖 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) ->UITableViewCell {let cell = tableView.dequeueReusableCell(withIdentifier: "NotesCell", for: indexPath) as!笔记单元格让 m = NotesModel()如果 indexPath.row == 3 {m.name = "这是一个很长的标题.它将演示当文本足够长以换行到多行时如何自动调整单元格高度."} 别的 {m.name = "标题 \(indexPath.row)"}cell.configure(with: m)返回单元格}}

结果:

After reading Ray Wenderlich guide for "Self-sizing Table View Cells" as well as this question and answers to it, I've decided to ask all of you for a help.

Have a programmically created cell:

import UIKit

class NotesCell: UITableViewCell {
lazy private var cellCaption: UILabel = {
    let label = UILabel()

    label.translatesAutoresizingMaskIntoConstraints = false
    label.font = UIFont.systemFont(ofSize: 20, weight: UIFont.Weight.medium)
    label.numberOfLines = 0
    label.lineBreakMode = .byWordWrapping

    return label
}()

func configure(with note: NotesModel) {
    cellCaption.text = note.name

    contentView.addSubview(cellCaption)
}

override func layoutSubviews() {
    super.layoutSubviews()

    NSLayoutConstraint.activate([
        cellCaption.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 8),
        cellCaption.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 8),
        cellCaption.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -8),
//            cellCaption.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -8),
cellCaption.bottomAnchor.constraint(greaterThanOrEqualTo: contentView.bottomAnchor, constant: -8)
            ])

//        cellCaption.sizeToFit()
//        cellCaption.layoutIfNeeded()
}
}

The table view controller uses UITableViewAutomaticDimension in the delegate methods:

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

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

}

As a result, the longest caption is indicated fully, but the cell anyway has the same height as all other.

Some update!

I've already tried to put into viewDidLoad() following code:

tableView.rowHeight = 44
tableView.estimatedRowHeight = UITableViewAutomaticDimension

with enabling delegate methods and disabling them as well. The result is the same :(

解决方案

You're doing a number of things wrong, but the main point is your use of greaterThanOrEqualTo:.

Instead, it should be:

cellCaption.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -8),

Also, your current code is adding a new label as a subview every time you set the text. Cells are reused, so you only want to add the label when the cell is created.

Next, the correct properties for the table are:

    tableView.rowHeight = UITableViewAutomaticDimension
    tableView.estimatedRowHeight = 44

Put those two lines in viewDidLoad() of your table view controller, and do not implement heightForRowAt or estimatedHeightForRowAt functions. You can delete your extension entirely.

And finally, you only need to set the constraints once. Definitely NOT in layoutSubviews().

Here's a full example:

//
//  NotesTableViewController.swift
//
//  Created by Don Mag on 8/29/18.
//

import UIKit

class NotesModel: NSObject {
    var name: String = ""
}

class NotesCell: UITableViewCell {
    lazy private var cellCaption: UILabel = {
        let label = UILabel()

        label.translatesAutoresizingMaskIntoConstraints = false
        label.font = UIFont.systemFont(ofSize: 20, weight: UIFont.Weight.medium)
        label.numberOfLines = 0
        label.lineBreakMode = .byWordWrapping

        return label
    }()

    func configure(with note: NotesModel) {
        cellCaption.text = note.name
    }

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        commonInit()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    func commonInit() -> Void {

        contentView.addSubview(cellCaption)

        NSLayoutConstraint.activate([
            cellCaption.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 8),
            cellCaption.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 8),
            cellCaption.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -8),
            cellCaption.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -8),
            ])

    }

}

class NotesTableViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 44
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

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

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "NotesCell", for: indexPath) as! NotesCell

        let m = NotesModel()

        if indexPath.row == 3 {
            m.name = "This is a very long caption. It will demonstrate how the cell height is auto-sized when the text is long enough to wrap to multiple lines."
        } else {
            m.name = "Caption \(indexPath.row)"
        }

        cell.configure(with: m)

        return cell
    }

}

Result:

这篇关于UITableViewAutomaticDimension 不按预期工作.迅速的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆