为了实现您想要的,您需要:
- 将单元格的状态存储在数据源中,以便
collectionView(_:layout:sizeForItemAt:)
函数可以使用索引路径轻松访问它
- 更改单元格的存储状态后,您需要调用
reloadItems(at:)
集合视图的函数,传递单元格的索引路径,以更新单元格的大小。
您可以在以下代码中看到一个示例:
class TestCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var `switch`: UISwitch!
var action: ((Bool) -> Void)?
@IBAction func switchValueChanged(_ sender: UISwitch) {
action?(sender.isOn)
}
}
private let reuseIdentifier = "Cell"
class TestCollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
struct Item {
let color: UIColor
var scaledDown: Bool
}
var items: [Item] = [
.init(color: .red, scaledDown: false),
.init(color: .green, scaledDown: false),
.init(color: .black, scaledDown: false),
.init(color: .orange, scaledDown: false),
.init(color: .yellow, scaledDown: false),
.init(color: .gray, scaledDown: false),
.init(color: .darkGray, scaledDown: false),
.init(color: .lightGray, scaledDown: false),
]
// MARK: UICollectionViewDataSource
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return items.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! TestCollectionViewCell
let item = items[indexPath.item]
cell.switch.isOn = item.scaledDown
cell.backgroundColor = item.color
cell.action = { [weak self] (isOn: Bool) in
guard let self = self else { return }
self.items[indexPath.item].scaledDown = isOn
collectionView.reloadItems(at: [indexPath])
}
return cell
}
// MARK: - UICollectionViewDelegateFlowLayout
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let dynamicHeight: CGFloat = 200
if items[indexPath.item].scaledDown {
return CGSize(width: view.frame.width, height: (dynamicHeight / 2))
}
return CGSize(width: view.frame.width, height: dynamicHeight)
}
}
