【问题标题】:UITableView's height its content with Auto Layout but limit UITableView heightUITableView 的高度其内容与自动布局但限制 UITableView 高度
【发布时间】:2021-08-28 18:04:21
【问题描述】:

我在UIViewController 中有一个UITableViewUIButton

UIViewController -> UIView -> UITableView
                           -> UIButton

UITableView 高度设置为根据其固有内容大小进行相应更改。当 UITableView 中有更多行数时,高度会增加,但我不想增加,以至于 UIButton 不可见。我不想在那个UIViewController 中有UIScrollView。 UIButton 的约束设置为距底部 25 像素,距 UITbaleView 25 像素,宽度设置为屏幕宽度的 70%。我将 UITableView 的约束设置为距顶部 10 像素,宽度与 superview 相同,高度设置为 590。我不确定如何设置优先级,以便 UIButton 可见,即使 UITableView 中有更多行数。

我正在使用下面的代码来增加 UITableView 的高度

override func updateViewConstraints() {
        tableViewHeight.constant = TableIb.contentSize.height
        super.updateViewConstraints()
    }

【问题讨论】:

  • 如果表格视图和按钮之间没有 UI 元素,不清楚为什么不简单地设置表格视图底部距离按钮顶部 25 分?
  • @DonMag 是的,它设置为按钮上方的 25pts。表格视图和按钮之间没有 UI 元素。
  • 好的 - 那么,你为什么要尝试使用“改变高度”的表格视图?
  • 我希望按钮每次都位于 tableview 的底部。例如,当只有一行且行高为 60pts 时,按钮应为 85pts。

标签: ios swift uitableview uiviewcontroller


【解决方案1】:

约束你的按钮:

  • tableView 底部的 25 分
  • bottom lessThanOrEqualTo -25-pts from view bottom(安全区域)

为您的 tableViewHeight 约束设置优先级低于要求。

所以,例如:

    button.topAnchor.constraint(equalTo: tableView.bottomAnchor, constant: 25.0).isActive = true
    button.bottomAnchor.constraint(lessThanOrEqualTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -25.0).isActive = true
    
    // whatever you want to start your tableView height at...
    //  it doesn't really matter, as I assume you'll be immediately
    //  changing its .constant value
    tableViewHeight = tableView.heightAnchor.constraint(equalToConstant: 30.0)
    tableViewHeight.priority = .defaultHigh
    tableViewHeight.isActive = true

该按钮将“粘住”tableView 底部的 25 点,当您更改 tableViewHeight.constant 时,它会“按下按钮”,但直到它距离视图底部 25 点(安全区)。

作为旁注,养成使用 Points 而不是 Pixelsview width 而不是 的习惯屏幕宽度


或者,将您的按钮嵌入UIView 并将该视图设置为viewForFooterInSection。它将“粘”在 tableView 的底行,但在 tableView 需要滚动时保持可见。

这将使您无需不断调整 tableView 的大小。

【讨论】:

  • 谢谢。我能够使用按钮的 GreaterThanOrEqualTo 约束来做到这一点。
猜你喜欢
  • 2011-12-09
  • 2018-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-12
  • 1970-01-01
相关资源
最近更新 更多