【发布时间】:2023-03-31 04:13:01
【问题描述】:
我正在尝试制作一个比使用 UICollectionView 完成某些小任务更容易制作网格的 UIControl。我正在使用 UIStackViews 的 UIStackView。那是垂直堆栈(列)的水平容器。问题是我需要一列作为扩展列来填充额外的空间。 UIStackView 是否尊重 setContentHuggingPriority 的设置? ,在这种情况下是我的垂直列之一。
我已经包含了一个游乐场来重现这个问题。
Link to visual showing the UILabel Grid where only one column should fill horizontally
这里是操场代码:
import Foundation
import UIKit
import PlaygroundSupport
class ViewController : UIViewController {
override func loadView() {
let view = UIView()
view.backgroundColor = .white
self.view = view
let labMatrix = LabelMatrix( rows: 4, columns: 4)
self.view.addSubview( labMatrix)
labMatrix.labMatrix[0][0].text = "Test"
labMatrix.frame = CGRect(x: 0, y: 0, width: 360, height: 520)
}
}
class LabelMatrix : UIStackView {
let rowCount : Int
let colCount : Int
var labMatrix = [[UILabel]]()
required init(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init ( rows: Int , columns : Int ) {
rowCount = rows
colCount = columns
super.init(frame:.zero)
create()
}
func create() {
var columns : [UIStackView] = [UIStackView]()
var rows : [UILabel] = [UILabel]()
for acol in 0..<colCount {
rows.removeAll()
for arow in 0..<rowCount {
let lab = UILabel()
// lab.translatesAutoresizingMaskIntoConstraints = false
rows.append( lab )
let str = "(\(arow),\(acol))"
lab.text = str
if !(arow%2 == 0) {
lab.backgroundColor = .lightGray
} else {
lab.backgroundColor = .yellow
}
if arow == rowCount-1 {
print("This should make last row stretch vertically to fill any extra vertical space")
// lab.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 20), for: .vertical)
lab.setContentHuggingPriority(UILayoutPriority(rawValue: 20), for:.vertical)
}
}
labMatrix.append( rows )
let curCol = UIStackView(arrangedSubviews: rows)
columns.append( curCol )
curCol.axis = .vertical
curCol.distribution = .fill
curCol.spacing = 2
curCol.alignment = .center
if acol == colCount-1 {
print("TODO Fix This. It should make only the last column(e.g. uistackview) strech to fill extra space")
curCol.setContentHuggingPriority(UILayoutPriority(rawValue: 20), for:.horizontal)
}
}
for col in columns {
self.addArrangedSubview( col )
}
self.axis = .horizontal
self.distribution = .fill
self.alignment = .top
self.spacing = 4
}
}
PlaygroundPage.current.liveView = ViewController()
【问题讨论】:
标签: ios swift cocoa-touch uistackview