所以我在 stackView 中有一個集合視圖,還有兩個 UIView,stackView 是一個 scrollView 的子視圖。我希望我的 collectionView 動態調整其高度并且不影響堆疊視圖中的其他視圖。我制作了一個圖表,顯示了我想要實作的目標,到目前為止......沒有成功,其他兩個視圖一直被拉長,或者 collectionView 似乎并不完全在中間。有沒有人可以幫助我?請。
約束代碼:
private func setupView() {
view.addSubview(scrollView)
scrollView.addSubview(mainStack)
headerStackView.addArrangedSubview(titleLabel)
footerStackView.addArrangedSubview(footerLabel)
mainStack.addArrangedSubview(headerStackView)
mainStack.addArrangedSubview(collectionView)
mainStack.addArrangedSubview(footerStackView)
let layoutGuide = view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
collectionView.heightAnchor.constraint(equalToConstant: 500),
scrollView.topAnchor.constraint(equalTo: layoutGuide.topAnchor),
scrollView.bottomAnchor.constraint(equalTo: layoutGuide.bottomAnchor),
scrollView.leadingAnchor.constraint(equalTo: layoutGuide.leadingAnchor, constant: 16),
scrollView.trailingAnchor.constraint(equalTo: layoutGuide.trailingAnchor, constant: -16),
mainStack.widthAnchor.constraint(equalTo: scrollView.widthAnchor),
mainStack.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 16),
mainStack.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
mainStack.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),
mainStack.bottomAnchor.constraint(equalTo: layoutGuide.bottomAnchor)
])
}
集合視圖和 StackView 代碼:
private lazy var collectionView: UICollectionView = {
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.backgroundColor = .white
collectionView.register(CustomCell.self, forCellWithReuseIdentifier: CustomCell.reuseId)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.showsVerticalScrollIndicator = false
collectionView.isScrollEnabled = false
return collectionView
}()
private lazy var mainStack: UIStackView = {
let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .vertical
stackView.spacing = 16
stackView.distribution = .fill
return stackView
}()
代理功能:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
let collectionViewSize = collectionView.frame.size.width - 16
let collectionViewHeightSize = collectionView.frame.size.height
return CGSize(width: collectionViewSize/2, height: collectionViewHeightSize / 2)
}
這是我的圖表:

uj5u.com熱心網友回復:
這一行是錯誤的:
mainStack.bottomAnchor.constraint(equalTo: layoutGuide.bottomAnchor)
上面寫著“無論滾動如何,都將 mainStack 底部保持在視圖的底部。
它應該是:
mainStack.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor)
現在mainStack成為滾動視圖的“可滾動內容”。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/439959.html
標籤:IOS 迅速 uicollectionview 约束 堆栈视图
