我建议...
- 向您的单元格添加一个子视图作为集合视图“容器”
- 设置其
.clipsToBounds = true
- 用
.constant = 0给它一个高度限制
- 用
.constant = 0给collectionView一个高度约束
- 当您知道所需的collectionViewCell 高度时,设置collectionView 的约束
.constant,以便加载单元格
- 为“容器”视图的高度约束设置动画以展开/折叠
从“容器”视图本身开始......一旦你让它正确展开/折叠,然后添加到集合视图中。
编辑这是一个非常基本的动画展开/折叠表格视图单元示例。
数据结构 - 键和值字符串、“高度”属性(可能在您知道该行的集合视图的高度时设置)和“扩展”属性标志。
struct DemoStruct {
var key: String = ""
var value: String = ""
var cvHeight: CGFloat = 0
var expanded: Bool = false
}
单元格类 - 两个标签,展开/折叠按钮,标签下方的“容器”视图:
class SampleTVCell: UITableViewCell {
// always visible elements
let keyLabel = UILabel()
let valLabel = UILabel()
let btn = UIButton()
// this will either hold the collectionView
// or be replaced by the collectionView
let containerView = UIView()
// will be set by the data
var containerHeight: NSLayoutConstraint!
// constraints for expanded/collapsed states
var expandedConstraint: NSLayoutConstraint!
var collapsedConstraint: NSLayoutConstraint!
// down/up chevrons
var expandImg: UIImage!
var collapseImg: UIImage!
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
func commonInit() -> Void {
// make sure we get down/up button images
guard let imgD = UIImage(systemName: "chevron.down"),
let imgU = UIImage(systemName: "chevron.up")
else {
fatalError("Bad image loading!")
}
expandImg = imgD
collapseImg = imgU
// covers the bottom of the container view when cell is "collapsed"
let coverView = UIView()
coverView.backgroundColor = .white
[keyLabel, valLabel, btn, containerView, coverView].forEach { v in
v.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(v)
}
// set as desired
keyLabel.font = .systemFont(ofSize: 20.0, weight: .bold)
valLabel.font = .italicSystemFont(ofSize: 18.0)
// use the built-in layout margins
let g = contentView.layoutMarginsGuide
// .constant will be set by data
containerHeight = containerView.heightAnchor.constraint(equalToConstant: 0.0)
// constrain bottom of valLabel to bottom of margins
// priority will be updated when expanded/collapsed
collapsedConstraint = valLabel.bottomAnchor.constraint(equalTo: g.bottomAnchor)
collapsedConstraint.priority = .defaultHigh
// constrain bottom of containerView to bottom of margins
// priority will be updated when expanded/collapsed
expandedConstraint = containerView.bottomAnchor.constraint(equalTo: g.bottomAnchor)
expandedConstraint.priority = .defaultLow
NSLayoutConstraint.activate([
// button at upper-right
btn.topAnchor.constraint(equalTo: g.topAnchor),
btn.trailingAnchor.constraint(equalTo: g.trailingAnchor),
btn.heightAnchor.constraint(equalToConstant: 32.0),
btn.widthAnchor.constraint(equalTo: btn.heightAnchor, multiplier: 1.5),
// keyLabel at upper-left
keyLabel.topAnchor.constraint(equalTo: g.topAnchor),
keyLabel.leadingAnchor.constraint(equalTo: g.leadingAnchor),
keyLabel.trailingAnchor.constraint(equalTo: btn.leadingAnchor, constant: -8.0),
// valLabel aligned and below keyLabel
valLabel.topAnchor.constraint(equalTo: keyLabel.bottomAnchor, constant: 4.0),
valLabel.leadingAnchor.constraint(equalTo: g.leadingAnchor),
valLabel.trailingAnchor.constraint(equalTo: btn.leadingAnchor, constant: -8.0),
// containerView below valLabel
containerView.topAnchor.constraint(equalTo: valLabel.bottomAnchor, constant: 8.0),
containerView.leadingAnchor.constraint(equalTo: g.leadingAnchor),
containerView.trailingAnchor.constraint(equalTo: g.trailingAnchor),
// activate our "control" constraints
collapsedConstraint,
expandedConstraint,
containerHeight,
// cover view sits at the very bottom of the contentView
// to cover the top part of the containerView
// when cell is "collapsed"
coverView.leadingAnchor.constraint(equalTo: g.leadingAnchor),
coverView.trailingAnchor.constraint(equalTo: g.trailingAnchor),
coverView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
coverView.heightAnchor.constraint(equalToConstant: contentView.layoutMargins.bottom),
])
// we don't want the labels to stretch or compress vertically
keyLabel.setContentCompressionResistancePriority(.required, for: .vertical)
valLabel.setContentCompressionResistancePriority(.required, for: .vertical)
keyLabel.setContentHuggingPriority(.required, for: .vertical)
valLabel.setContentHuggingPriority(.required, for: .vertical)
// action for button
btn.addTarget(self, action: #selector(btnTap(_:)), for: .touchUpInside)
// Important!
contentView.clipsToBounds = true
// so we can see the containerView
// until we replace it with or add a collectionView as a subview
containerView.backgroundColor = .systemYellow
}
// closure so we can tell the controller we want the cell
// to collapse or expand
var expand: ((Bool)->())?
private var expanded: Bool = false {
didSet {
// set collapsed/expanded constraint priorities
collapsedConstraint.priority = expanded ? .defaultLow : .defaultHigh
expandedConstraint.priority = expanded ? .defaultHigh : .defaultLow
// update button image
btn.setImage(expanded ? collapseImg : expandImg, for: [])
}
}
func fillData(_ d: DemoStruct) -> Void {
keyLabel.text = d.key
valLabel.text = d.value
containerHeight.constant = d.cvHeight
expanded = d.expanded
}
@objc func btnTap(_ sender: Any?) -> Void {
expanded.toggle()
// tell the controller our expanded state changed
expand?(expanded)
}
}
控制器类 - 生成 20 行数据,具有不同的“集合视图”高度。
class DemoTableViewController: UITableViewController {
var theData: [DemoStruct] = []
override func viewDidLoad() {
super.viewDidLoad()
// create 20 rows of sample data
theData = (1...20).map { DemoStruct(key: "Key \($0)", value: "Value \($0)", cvHeight: 40.0, expanded: false) }
// vary the containerView heights
// this will end up being the collectionView heights
let demoHeights: [CGFloat] = [
40, 160, 80, 120,
]
for i in 0..<theData.count {
theData[i].cvHeight = demoHeights[i % demoHeights.count]
}
tableView.register(SampleTVCell.self, forCellReuseIdentifier: "stvc")
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return theData.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let c = tableView.dequeueReusableCell(withIdentifier: "stvc", for: indexPath) as! SampleTVCell
let d = theData[indexPath.row]
c.fillData(d)
// set the closure
c.expand = { isExpanded in
// update data
self.theData[indexPath.row].expanded = isExpanded
// this tells the tableView to animate cell height changes
tableView.performBatchUpdates(nil, completion: nil)
}
return c
}
}