使用插入单元格到表中时,UITableViewCell 不使用自动布局高度

2023-12-25

背景

我按照说明使用 purelayout 以编程方式创建 UITableViewCellshere https://stackoverflow.com/a/18746930/766570,它基本上表明您必须在单元格上设置顶部/底部约束,然后使用

self.tableView.rowHeight = UITableViewAutomaticDimension;

为了得到正确的结果:

Problem

一切工作正常,除了当我将新行插入 tableView 时。我得到这样的效果:https://youtu.be/eTGWsxwDAdk https://youtu.be/eTGWsxwDAdk

解释一下:一旦我单击其中一个提示单元格,表格就应该插入一个司机小费排。但是您会注意到,当我刷新该部分(通过单击提示框)时,所有单元格的高度都会莫名其妙地增加,但是当我再次单击提示框时,它们会恢复到正常高度 这是用这段代码完成的

self.tableView.beginUpdates()
self.tableView.reloadSections(IndexSet(integer:1), with: .automatic)
self.tableView.endUpdates()

这是 cellfor row 的实现

// init table
self.tableView.register(OrderChargeTableViewCell.self,
                            forCellReuseIdentifier: OrderChargeTableViewCell.regularCellIdentifier)
self.tableView.register(OrderChargeTableViewCell.self,
                            forCellReuseIdentifier: OrderChargeTableViewCell.boldCellIdentifier)

self.tableView.estimatedRowHeight = 25
self.tableView.rowHeight = UITableViewAutomaticDimension

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    var cell: OrderChargeTableViewCell?
    if (indexPath.row == filteredModel.count-1) {
        cell = tableView.dequeueReusableCell(withIdentifier: OrderChargeTableViewCell.boldCellIdentifier,
                                             for: indexPath) as? OrderChargeTableViewCell
    } else if (indexPath.row < filteredModel.count) {
        cell = tableView.dequeueReusableCell(withIdentifier: OrderChargeTableViewCell.regularCellIdentifier,
                                             for: indexPath) as? OrderChargeTableViewCell
    }

    // add data to cell labels
    return cell!
}

这是 UITableViewCell 本身的代码:

最终类 OrderChargeTableViewCell: UITableViewCell {

// MARK: - init
static let boldCellIdentifier = "TTOrderDetailBoldTableViewCell"
static let regularCellIdentifier = "TTOrderDetailRegularTableViewCell"

private var didSetupConstraints = false
.. 

override init(style: UITableViewCellStyle, reuseIdentifier: String?) {

    self.keyLabel = TTRLabel()
    self.valueLabel = TTRLabel()

    if (reuseIdentifier == OrderChargeTableViewCell.regularCellIdentifier) {
        self.isCellStyleBold = false
    } else if (reuseIdentifier == OrderChargeTableViewCell.boldCellIdentifier) {
        self.isCellStyleBold = true
    } else {
        self.isCellStyleBold = false
        assertionFailure( "Attempt to create an OrderCharge cell with the wrong cell identifier: \(String(describing: reuseIdentifier))")
    }

    super.init(style: style, reuseIdentifier: reuseIdentifier)


    contentView.addSubview(keyLabel)
    contentView.addSubview(valueLabel)

}

override func updateConstraints()
{
    if !didSetupConstraints {
        if (isCellStyleBold) {
            self.applyBoldFormatting()
        } else {
            self.applyRegularFormatting()
        }

        didSetupConstraints = true
    }

    super.updateConstraints()
}
public func applyBoldFormatting() {
    keyLabel.font = .ttrSubTitle
    valueLabel.font = .ttrBody

    keyLabel.autoPinEdge(.leading, to: .leading, of: contentView, withOffset: 15)
    keyLabel.autoAlignAxis(.vertical, toSameAxisOf: contentView)

    keyLabel.autoPinEdge(.top, to: .top, of: contentView, withOffset: 8)
    keyLabel.autoPinEdge(.bottom, to: .bottom, of: contentView, withOffset: -8)

    valueLabel.autoPinEdge(.trailing, to: .trailing, of: contentView, withOffset: -15)
    valueLabel.autoAlignAxis(.baseline, toSameAxisOf: keyLabel)
}

public func applyRegularFormatting() {
    keyLabel.font = .ttrCaptions
    valueLabel.font = TTRFont.Style.standard(.h3).value

    keyLabel.autoPinEdge(.leading, to: .leading, of: contentView, withOffset: 15)
    keyLabel.autoAlignAxis(.vertical, toSameAxisOf: contentView)

    keyLabel.autoPinEdge(.top, to: .top, of: contentView, withOffset: 6)
    keyLabel.autoPinEdge(.bottom, to: .bottom, of: contentView, withOffset: -4)

    valueLabel.autoPinEdge(.trailing, to: .trailing, of: contentView, withOffset: -15)
    valueLabel.autoAlignAxis(.baseline, toSameAxisOf: keyLabel)
}

the driver tip row that gets inserted has the standard 44 pixel height of a cell: enter image description here

whereas the other (properly formatted) cells have the 25 height: enter image description here


虽然您遵循的 StackOverflow 答案有很多赞成票,但您似乎采取了一个没有得到很好解释的要点(并且可能已经过时),我认为这可能是导致您出现问题的原因。

您会发现许多评论/帖子/文章指出您应该在中添加约束updateConstraints(), 然而,苹果的文档 https://developer.apple.com/documentation/uikit/uiview/1622512-updateconstraints还指出:

重写此方法以优化对约束的更改。

Note

在发生影响的更改后立即更新约束几乎总是更干净、更容易。例如,如果您想更改约束以响应按钮点击,请直接在按钮的操作方法中进行更改。

仅当更改约束太慢或视图产生大量冗余更改时,才应重写此方法。

我认为如果您添加子视图,您会在尝试的过程中获得更好的结果and当你的单元初始化时它们的限制。

这是一个简单的示例,其布局与您所显示的布局类似。它创建一个包含 2 个部分的表格 - 第一个部分有一行带有“显示/隐藏”按钮。点击后,第二部分将添加/删除“驾驶员提示”行。

//
//  InsertRemoveViewController.swift
//
//  Created by Don Mag on 12/4/18.
//

import UIKit

struct MyRowData {
    var title: String = ""
    var value: CGFloat = 0.0
}

class OrderChargeTableViewCell: UITableViewCell {

    static let boldCellIdentifier: String = "TTOrderDetailBoldTableViewCell"
    static let regularCellIdentifier: String = "TTOrderDetailRegularTableViewCell"

    var keyLabel: UILabel = {
        let v = UILabel()
        v.translatesAutoresizingMaskIntoConstraints = false
        return v
    }()

    var valueLabel: UILabel = {
        let v = UILabel()
        v.translatesAutoresizingMaskIntoConstraints = false
        return v
    }()

    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(keyLabel)
        contentView.addSubview(valueLabel)

        let s = type(of: self).boldCellIdentifier

        if self.reuseIdentifier == s {

            NSLayoutConstraint.activate([
                keyLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 8.0),
                keyLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -8.0),
                keyLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 15.0),

                valueLabel.centerYAnchor.constraint(equalTo: keyLabel.centerYAnchor, constant: 0.0),
                valueLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -15.0),
                ])

            keyLabel.font = UIFont.systemFont(ofSize: 15, weight: .bold)
            valueLabel.font = UIFont.systemFont(ofSize: 15, weight: .bold)

        } else {

            NSLayoutConstraint.activate([
                keyLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 6.0),
                keyLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -4.0),
                keyLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 15.0),

                valueLabel.centerYAnchor.constraint(equalTo: keyLabel.centerYAnchor, constant: 0.0),
                valueLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -15.0),
                ])

            keyLabel.font = UIFont.systemFont(ofSize: 12, weight: .bold)
            valueLabel.font = UIFont.systemFont(ofSize: 12, weight: .regular)

        }

    }

}

class TipCell: UITableViewCell {

    var callBack: (() -> ())?

    var theButton: UIButton = {
        let b = UIButton()
        b.translatesAutoresizingMaskIntoConstraints = false
        b.setTitle("Tap to Show/Hide Add Tip row", for: .normal)
        b.setTitleColor(.blue, for: .normal)
        b.backgroundColor = .yellow
        return b
    }()

    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(theButton)

        NSLayoutConstraint.activate([
            theButton.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 20.0),
            theButton.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -20.0),
            theButton.centerXAnchor.constraint(equalTo: contentView.centerXAnchor, constant: 0.0),
            ])

        theButton.addTarget(self, action: #selector(btnTapped(_:)), for: .touchUpInside)

    }

    @objc func btnTapped(_ sender: Any?) -> Void {
        callBack?()
    }

}

class InsertRemoveViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var myData = [
        MyRowData(title: "SUBTOTAL", value: 4),
        MyRowData(title: "DELIVERY CHARGE", value: 1.99),
        MyRowData(title: "DISCOUNT", value: -1.99),
        MyRowData(title: "TOTAL", value: 4),
        ]

    var tableView: UITableView = {
        let v = UITableView()
        v.translatesAutoresizingMaskIntoConstraints = false
        return v
    }()


    func tipRowShowHide() {

        let iPath = IndexPath(row: 3, section: 1)

        if myData.count == 4 {
            myData.insert(MyRowData(title: "DRIVER TIP", value: 2.0), at: 3)
            tableView.insertRows(at: [iPath], with: .automatic)
        } else {
            myData.remove(at: 3)
            tableView.deleteRows(at: [iPath], with: .automatic)
        }

    }

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.register(OrderChargeTableViewCell.self,
                           forCellReuseIdentifier: OrderChargeTableViewCell.regularCellIdentifier)
        tableView.register(OrderChargeTableViewCell.self,
                           forCellReuseIdentifier: OrderChargeTableViewCell.boldCellIdentifier)

        tableView.register(TipCell.self, forCellReuseIdentifier: "TipCell")

        tableView.delegate = self
        tableView.dataSource = self

        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 25

        view.backgroundColor = .red

        view.addSubview(tableView)

        NSLayoutConstraint.activate([
            tableView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 200.0),
            tableView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -20.0),
            tableView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 20.0),
            tableView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -20.0),
            ])

    }

    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return " "
    }

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

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return section == 0 ? 1 : myData.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        if indexPath.section == 0 {

            let cell = tableView.dequeueReusableCell(withIdentifier: "TipCell", for: indexPath) as! TipCell

            cell.callBack = {
                self.tipRowShowHide()
            }

            return cell

        }

        var cell: OrderChargeTableViewCell?

        if indexPath.row == myData.count - 1 {

            cell = tableView.dequeueReusableCell(withIdentifier: OrderChargeTableViewCell.boldCellIdentifier,
                                                 for: indexPath) as? OrderChargeTableViewCell

        } else {

            cell = tableView.dequeueReusableCell(withIdentifier: OrderChargeTableViewCell.regularCellIdentifier,
                                                 for: indexPath) as? OrderChargeTableViewCell

        }

        cell?.keyLabel.text = myData[indexPath.row].title

        let val = myData[indexPath.row].value
        cell?.valueLabel.text = String(format: "%0.02f USD", val)

        return cell!

    }

}

这是结果:

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用插入单元格到表中时,UITableViewCell 不使用自动布局高度 的相关文章

  • 你能以编程方式调用 Siri 吗?

    我想创建一个 UITextView 的子类 其中包含一个自定义按钮来调用 Siri 用于其语音到文本的文本输入 这可能吗 我不介意是否显示键盘 我只想提供自己的按钮来打开 Siri 不幸的是 你不能这样做 从 iOS 6 0 开始 使用 S
  • JS:event.touches 属性如何工作?

    我不明白如何使用 event touches 属性 例如 要获取 iPad iPhone 上的手指数量 您应该使用 event touches length 那么为什么这个示例代码不起作用呢 image bind touchstart fu
  • 致命错误:Swift 2.0 不支持与自身交换位置

    我有这个扩展 它将创建一个新数组 其中包含来自给定数组的随机数组组 extension Array var shuffle Element var elements self for index in 0
  • 是否可以“重新设计”IOS 日期选择器?

    我需要一个自定义日期选择器 本质上只是想删除 IOS 版本中的图形 但保留 3 列日期滚动 是否需要从头开始重新构建 所有研究都表明是 或者是否可以仅禁用或交换图像 我自己还没有尝试过 但也许您可以在日期选择器上方添加一个 UIImageV
  • 获取请求,iOS

    我需要执行此 GET 请求 http api testmy co il api sync BID 1049 ClientCode 3847 Discount 2 34 Service 0 Items Name Tax Price 2 11
  • 从故事板向 UILabel 属性字符串添加下划线失败

    从故事板中我选择有问题的 UILabel 然后在属性检查器 gt 标签 gt 我选择 属性 同样在属性检查器 gt 标签 gt 文本 gt 我选择内容 然后我单击字体图标并选择下划线 基本上 我从弹出的 字体 窗口中选择的任何更改都不会生效
  • 如何在 ios7 中的 UITextfield 中禁用复制/粘贴选项

    I tried implementation UITextField DisableCopyPaste BOOL canPerformAction SEL action withSender id sender return NO retu
  • iOS 中的泰米尔字体

    我尝试安装泰米尔字体名称Bamini ttf in xcode 4 2我做了具体的改变info plist 但它没有显示在界面生成器中 任何人都可以帮我解决这个问题吗 据我所知 您安装的新字体永远不会在界面生成器中列出 但是您可以在项目中使
  • iOS:同时录制和播放的示例代码

    我正在为多轨录音机设计一个简单的概念验证 明显的起点是从文件 A caf 播放到耳机 同时将麦克风输入记录到文件 B caf 这个问题 同时录制和播放音频 https stackoverflow com questions 4215180
  • 使用 Accelerate 框架 32 位与 64 位进行 swift 矩阵乘法

    我正在尝试使用 Accelerate 框架在 Swift 中进行矩阵乘法 使用了vDSP mmulD 这在 iPhone6 6 plus iPad Air 模拟器 所有 64 位架构 中完美运行 但不适用于任何 32 位架构设备 看来 32
  • 图像持久化和延迟加载与 Dispatch_Async 的冲突

    我正在开发一个提要阅读器 我通过使用 nsxmlparser 解析 rss 提要来完成它 我还有从 CDATA 块中获取的缩略图对象 void parser NSXMLParser parser foundCDATA NSData CDAT
  • iOS 10 中未显示锁定屏幕上基于信标的应用程序建议

    我的应用程序使用后台信标扫描 我已经写了locationManager requestAlwaysAuthorization and locationManager startMonitoring for region 在我的代码中 当我打
  • iOS9 按需访问和下载资源

    我正在尝试实现新的 iOS9 功能应用程序细化 我了解如何在 Xcode 7 中标记图像并启用按需资源 但我不明白如何在我的应用程序中实现 NSBundleResourceRequest 有人可以帮助我 我将不胜感激 大部分信息都可以在 A
  • 需要从另一个viewController调用其他viewController中的方法

    我有一个具有多个视图控制器的应用程序 其中一些视图控制器包含运行各种任务的方法 我需要做的是 当初始 viewController 加载时 在其他 viewController 中调用这些方法 以便它们在后台运行 但是 我在执行此操作时遇到
  • 如何使用mapkit和swift在设定位置覆盖一个圆圈

    我在尝试弄清楚如何在与用户位置不同的所需位置显示透明圆形或矩形时遇到困难 我是 Mapkit 的初学者 所以提前致谢 class FirstViewController UIViewController MKMapViewDelegate
  • 如何让 UIPickerView 滑动到屏幕的一半?

    when someone clicks clothing I want the UIPickerView to slide up as in the example as follows 有人可以展示代码示例吗 正如 dsc 和 Jason
  • presentOpenInMenuFromBarButtonItem:不会导致菜单出现

    我试图通过以下方式显示 打开方式 菜单UIDocumentInteractionController and presentOpenInMenuFromBarButtonItem 这不会提出UIDocumentInteractionCont
  • CAltimeter 回调永远不会触发

    使用我的 6 我一直在尝试使用 CoreMotion 的新 CMAltimeter 读取相对高度和压力 但是回调永远不会触发 我有一个非常相似的设置 它使用加速度计 陀螺仪和磁力计 他们似乎都工作得很好 想知道是否有人设法阅读 void v
  • 使用 XCode 5 的 iPhone 弹出窗口视图

    我想重复使用 iPhone 中描述的弹出窗口这个视频 http youtu be 1iykxemuxbk这正是我所需要的 问题是我无法绑定UIViewController弹出窗口的属性UIViewController就像视频中一样 该视频的
  • PerformSegueWithIdentifier 不会产生带有标识符错误的 Segue

    我很难让 PerformSegueWithIdentifier 正常工作 我不断得到 Receiver

随机推荐