【发布时间】:2018-10-15 15:08:24
【问题描述】:
我有一个关于如何控制 UICollectionViewCell 的调整大小动画的问题。为了更清楚,我想知道如何设置动画的持续时间和曲线。我有一个简单的 UICollectionView 流布局和一个包含按钮的单元格。点击按钮会导致单元格的高度发生变化。
这是我的代码:
class ViewController: UICollectionViewController {
var isExpanded = false
var cv: UICollectionView {
get {
return collectionView!
}
}
override func viewDidLoad() {
super.viewDidLoad()
if let layout = collectionView?.collectionViewLayout as? UICollectionViewFlowLayout {
layout.estimatedItemSize = CGSize(width: collectionView!.frame.width, height: 400.0)
}
collectionView?.delegate = self
collectionView?.dataSource = self
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CollectionViewCell
cell.parent = self
return cell
}
}
extension ViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let cell = collectionView.cellForItem(at: indexPath) as? CollectionViewCell
/*
Need to calculate cell's height.
*/
return isExpanded ? CGSize(width: collectionView.frame.width, height: 400) : CGSize(width: collectionView.frame.width, height: 200)
}
}
这是我的单元格的代码
class CollectionViewCell: UICollectionViewCell {
var heightConstraint: NSLayoutConstraint!
var isExpanded = false
var parent: ViewController! {
didSet {
contentView.widthAnchor.constraint(equalToConstant: parent.view.frame.width).isActive = true
heightConstraint = NSLayoutConstraint(item: contentView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 200.0)
contentView.addConstraint(heightConstraint)
}
}
@IBOutlet weak var height: NSLayoutConstraint!
override func awakeFromNib() {
super.awakeFromNib()
contentView.translatesAutoresizingMaskIntoConstraints = false
}
@IBAction func expand(_ sender: Any) {
self.parent.cv.performBatchUpdates({
//This UIView animate block doesn't matter anything actually.
UIView.animate(withDuration: 10.5, animations: {[unowned self] in
self.isExpanded = !self.isExpanded
self.heightConstraint.constant = self.isExpanded ? 400.0 : 200.0
self.layoutIfNeeded()
}, completion: nil)
}, completion: nil)
}
如您所见,我决定为这个示例制作相当长的动画,因此,我注意到 UIView.animate 块实际上不会影响单元格的调整大小动画。我想我应该寻找 CAAnimation 或类似的东西。很高兴听到任何想法!谢谢。
【问题讨论】:
标签: ios swift uicollectionview uicollectionviewcell uicollectionviewlayout