UITableView 没有固有的高度/宽度,因此当放置在没有任何高度/宽度信息的UIStackView 中时,它将提供默认大小。即,如果您在堆栈中的最高视图高度为 60,那么 tableView 也将是 60。
您可以通过在将 yearTable 添加到 UIStackView 之前给它一个高度限制来改变它,如下所示:
func fillStackView() {
//...
yearTable.translatesAutoresizingMaskIntoConstraints = false
yearTable.heightAnchor.constraint(equalToConstant: 150).isActive = true
allViews.append(yearTable)
//...
}
但请注意,如果您这样做,那么由于stackView.distribution = .fillEqually,您在UIStackView 中的所有其他视图也将变为150。
(额外)游乐场示例:
import UIKit
import PlaygroundSupport
class ViewController: UIViewController {
lazy var stackView: UIStackView = {
let stackView = UIStackView()
stackView.axis = .vertical
stackView.distribution = .fillEqually
stackView.spacing = 8
stackView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(stackView)
stackView.widthAnchor.constraint(equalToConstant: 200).isActive = true
return stackView
}()
let datasource = [1,2,3,4,5,6,7,8,9,10]
override func viewDidLoad() {
super.viewDidLoad()
appendLabel(text: "Hello, World!", color: .lightGray)
appendLabel(text: "Lorem\nipsum\ndolor\nsit", color: .gray)
appendTableView()
}
func appendLabel(text: String, color: UIColor) {
let label = UILabel()
label.backgroundColor = color
label.numberOfLines = 0
label.text = text
stackView.addArrangedSubview(label)
}
func appendTableView() {
let tableView = UITableView()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
tableView.dataSource = self
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.heightAnchor.constraint(equalToConstant: 150).isActive = true
stackView.addArrangedSubview(tableView)
}
}
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return datasource.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let item = datasource[indexPath.row]
cell.textLabel?.text = String(item)
return cell
}
}
let vc = ViewController()
vc.view.frame = CGRect(x: 0, y: 0, width: 320, height: 480)
PlaygroundPage.current.setLiveView(vc.view)
- 评论
tableView.heightAnchor.constraint(equalToConstant: 150).isActive = true查看区别