防止UIStackView压缩UITableView [英] Prevent UIStackView from compressing UITableView

查看:86
本文介绍了防止UIStackView压缩UITableView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将UITableView添加到垂直UIStackView中.该垂直的UIStackView在UIScrollView中.

I am adding a UITableView into vertical UIStackView. That vertical UIStackView is within a UIScrollView.

但是,除非我强加对表的明确的Height约束(显然我不想这样做),否则该表不会显示.

However the table is not displaying unless I force an explicit Height constraint on it which I obviously don't want to do.

根据此SO问题和答案 UITableView未显示在UIStackView内,这是因为"stackview尝试尽可能多地压缩内容"

According to this SO question and answer UITableView not shown inside UIStackView this is because "stackview tries to compress content as much as possible"

如果我将UILabel添加到StackView,它将显示正常. UITableView有一些特定的含义,但事实并非如此.我正在使用Xamarin并用代码创建UITableView

If I add a UILabel to the StackView it is displayed fine. There is something specific about the UITableView that means it is not. I am using Xamarin and creating the UITableView in code

this.recentlyOpenedPatientsTable = new UITableView()
{
    RowHeight = UITableView.AutomaticDimension,
    EstimatedRowHeight = 44.0f,
    AllowsMultipleSelectionDuringEditing = false,
    TranslatesAutoresizingMaskIntoConstraints = false,
    Editing = false,
    BackgroundColor = UIColor.Clear,
    TableFooterView = new UIView(),
    ScrollEnabled = false,
};   

UIScrollView固定在视图的顶部,底部,左侧和右侧,并且工作正常.需要我期望的高度.

The UIScrollView is pinned to the Top, Bottom, Left and Right of the View and works fine. It takes the Height I expect.

我尝试了这个SO问题中的两个建议,但都没有奏效.我找不到其他人遇到这个问题,这很奇怪.

I have tried both the suggestions in this SO question and neither have worked. I find it odd that I cannot find others having this issue.

还有其他建议吗?

推荐答案

这是一个非常基本的示例,使用UITableView子类使其根据内容自动调整高度.

Here is a very basic example, using a UITableView subclass to make it auto-size its height based on its content.

红色按钮(在水平堆栈视图中)是垂直堆栈视图中的第一个排列的子视图.

The red buttons (in a horizontal stack view) are the first arranged subView in the vertical stack view.

下一个表格(单元格的contentView的绿色背景,多行标签的黄色背景).

The table is next (green background for the cells' contentView, yellow background for a multi-line label).

最后排列的子视图是青色背景UILabel:

And the last arranged subView is a cyan background UILabel:

请注意,垂直堆栈视图从顶部,前导和尾部限制为40点,并且从底部至少限制为 .如果您在表格中添加了足够多的行以超过可用高度,则必须滚动查看其他行.

Note that the vertical stack view is constrained 40-pts from Top, Leading and Trailing, and at least 40-pts from the Bottom. If you add enough rows to the table to exceed the available height, you'll have to scroll to see the additional rows.

//
//  TableInStackViewController.swift
//
//  Created by Don Mag on 6/24/19.
//

import UIKit

final class ContentSizedTableView: UITableView {

    override var contentSize:CGSize {
        didSet {
            invalidateIntrinsicContentSize()
        }
    }

    override var intrinsicContentSize: CGSize {
        layoutIfNeeded()
        return CGSize(width: UIView.noIntrinsicMetric, height: contentSize.height)
    }

}

class TableInStackCell: UITableViewCell {

    let theLabel: UILabel = {
        let v = UILabel()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.backgroundColor = .yellow
        v.textAlignment = .left
        v.numberOfLines = 0
        return v
    }()

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        contentView.backgroundColor = .green

        contentView.addSubview(theLabel)

        NSLayoutConstraint.activate([

            theLabel.topAnchor.constraint(equalTo: contentView.layoutMarginsGuide.topAnchor, constant: 0.0),
            theLabel.bottomAnchor.constraint(equalTo: contentView.layoutMarginsGuide.bottomAnchor, constant: 0.0),
            theLabel.leadingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.leadingAnchor, constant: 0.0),
            theLabel.trailingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.trailingAnchor, constant: 0.0),

            ])

    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }


}

class TableInStackViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    let theStackView: UIStackView = {
        let v = UIStackView()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.axis = .vertical
        v.alignment = .fill
        v.distribution = .fill
        v.spacing = 8
        return v
    }()

    let addButton: UIButton = {
        let v = UIButton()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.setTitle("Add a Row", for: .normal)
        v.backgroundColor = .red
        return v
    }()

    let deleteButton: UIButton = {
        let v = UIButton()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.setTitle("Delete a Row", for: .normal)
        v.backgroundColor = .red
        return v
    }()

    let buttonsStack: UIStackView = {
        let v = UIStackView()
        v.axis = .horizontal
        v.alignment = .fill
        v.distribution = .fillEqually
        v.spacing = 20
        return v
    }()

    let theTable: ContentSizedTableView = {
        let v = ContentSizedTableView()
        v.translatesAutoresizingMaskIntoConstraints = false
        return v
    }()

    let bottomLabel: UILabel = {
        let v = UILabel()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.backgroundColor = .cyan
        v.textAlignment = .center
        v.numberOfLines = 0
        v.text = "This label is the last element in the stack view."
        // prevent label from being compressed when the table gets too tall
        v.setContentCompressionResistancePriority(.required, for: .vertical)
        return v
    }()

    var theTableData: [String] = [
        "Content Sized Table View",
        "This row shows that the cell heights will auto-size, based on the cell content (multi-line label in this case).",
        "Here is the 3rd default row",
    ]

    var minRows = 1

    let reuseID = "TableInStackCell"

    override func viewDidLoad() {
        super.viewDidLoad()

        minRows = theTableData.count

        view.addSubview(theStackView)

        NSLayoutConstraint.activate([

            // constrain stack view 40-pts from top, leading and trailing
            theStackView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 40.0),
            theStackView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 40.0),
            theStackView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -40.0),

            // constrain stack view *at least* 40-pts from bottom
            theStackView.bottomAnchor.constraint(lessThanOrEqualTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -40.0),

            ])

        buttonsStack.addArrangedSubview(addButton)
        buttonsStack.addArrangedSubview(deleteButton)

        theStackView.addArrangedSubview(buttonsStack)
        theStackView.addArrangedSubview(theTable)
        theStackView.addArrangedSubview(bottomLabel)

        theTable.delegate = self
        theTable.dataSource = self

        theTable.register(TableInStackCell.self, forCellReuseIdentifier: reuseID)

        addButton.addTarget(self, action: #selector(addRow), for: .touchUpInside)
        deleteButton.addTarget(self, action: #selector(deleteRow), for: .touchUpInside)

    }

    @objc func addRow() -> Void {
        // add a row to our data source
        let n = theTableData.count - minRows
        theTableData.append("Added Row: \(n + 1)")
        theTable.reloadData()
    }

    @objc func deleteRow() -> Void {
        // delete a row from our data source (keeping the original rows intact)
        let n = theTableData.count
        if n > minRows {
            theTableData.remove(at: n - 1)
            theTable.reloadData()
        }
    }

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

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: reuseID, for: indexPath) as! TableInStackCell
        cell.theLabel.text = theTableData[indexPath.row]
        return cell
    }

}

这篇关于防止UIStackView压缩UITableView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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