簡體   English   中英

如何根據內容調整 UIStackView 的大小?

[英]How to size a UIStackView depending on its content?

在框架根據其內容調整大小的意義上,我希望具有與<Table> HTML 標記類似的行為。

在我的上下文中,我使用 UIStackView 作為 UITableViewCell 的內容視圖。 由於單元格中的項目是各種信息,因此單元格的結果高度應該是可變的。

我的策略是以編程方式將單元格構建為帶有 .Vertical 軸的 UIStackView,如下代碼片段所示:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)

    let sv = UIStackView(frame: tableview.frame)
    sv.axis = .Vertical
    cell.addSubview(sv)
    for i in information {
        let l = UILabel()
        l.text = i
        sv.addSubViewAndArrange(l)
    }

    return cell
}

不幸的是,單元格大小無法根據內容調整,因​​此我必須自己設置單元格高度,如下所示:

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return cellHeight     // a constant
}

我怎么能解決這個問題?

UIStackView旨在根據內容增加其大小。 為了使其工作,您需要設置UIStackViewUITableViewCell之間的約束。 例如,如果UIStackView是第一項,而UITableViewCell是它的超級視圖,那么這就是界面生成器中約束的樣子:

在此處輸入圖像描述 在此處輸入圖像描述

如果您喜歡在代碼中設置約束,那也應該可以。
例如,假設stackViewcellView是名稱,那么上述約束的 Swift 代碼將如下所示:

stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.topAnchor.constraint(equalTo: cellView.topAnchor, constant: 0).isActive = true
stackView.bottomAnchor.constraint(equalTo: cellView.bottomAnchor, constant: 0).isActive = true
stackView.leadingAnchor.constraint(equalTo: cellView.leadingAnchor, constant: 0).isActive = true
stackView.trailingAnchor.constraint(equalTo: cellView.trailingAnchor, constant: 0).isActive = true

為了證明這將起作用,我將它用於cellForRowAt函數。 基本上,它在UIStackView中放置了一些UILabel並且標簽計數取決於行號。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "TableviewCell", for: indexPath) as! TableviewCell
    for i in 1...indexPath.row + 1 {
        let label = UILabel()
        label.text = "Row \(indexPath.row), Label \(i)"
        cell.stackView.addArrangedSubview(label)
    }
    return cell
}

這是最終結果:

https://github.com/yzhong52/AutosizeStackview

我構建了這個示例,希望對您有所幫助,我創建了一個 tableView,它使用一個包含 stackView 的單元格,並且在 stackView 中加載的視圖是從一個 nib 文件中獲取的

https://github.com/Joule87/stackView-within-TableViewCell

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM