我已经尝试了一些代码,但是并没有给出完美的动画,这是我的代码
func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {
UIView.animate(withDuration: 0.8) {
if let cell = self.subCategoryCollectionView.cellForItem(at: indexPath) as? LawyerSubCategoryCVC {
cell.transform = .init(scaleX: 1.5, y: 1.5)
}
}
}
点击收藏视图单元格,如何获得完美的动画?
答案 0 :(得分:0)
我认为您可以为所选项目设置单元格高度,这将对您有所帮助。
答案 1 :(得分:0)
import UIKit
extension UIColor {
static var random: UIColor {
return UIColor(red: .random(in: 0...1),
green: .random(in: 0...1),
blue: .random(in: 0...1),
alpha: 1.0)
}
}
class ViewController: UIViewController ,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
@IBOutlet weak var collectionView: UICollectionView!
var selectedIndex = 2
override func viewDidLoad() {
super.viewDidLoad()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath)
cell.contentView.backgroundColor = UIColor.random
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
self.selectedIndex = indexPath.row
collectionView.reloadData()
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let noOfCellsInRow = 4
let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
let totalSpace = flowLayout.sectionInset.left
+ flowLayout.sectionInset.right
+ (flowLayout.minimumInteritemSpacing * CGFloat(noOfCellsInRow - 1))
let size = Int((collectionView.bounds.width - totalSpace) / CGFloat(noOfCellsInRow))
if selectedIndex == indexPath.row {
return CGSize(width: size, height: size + 40)
}
return CGSize(width: size, height: size)
}
}
答案 2 :(得分:0)
要启动单元格,应更改单元格zPosition。 例如:
class MyCell: UICollectionViewCell {
override var isSelected: Bool {
didSet {
UIView.animate(withDuration: 0.3, delay: 0.0, options: .curveEaseOut, animations: {
self.layer.zPosition = self.isSelected ? 1 : -1
self.transform = self.isSelected ? CGAffineTransform(scaleX: 1.2, y: 1.2) : CGAffineTransform.identity
}, completion: nil)
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
layer.borderWidth = 1
layer.cornerRadius = 4
layer.borderColor = UIColor.clear.cgColor
layer.shadowOpacity = 0.2
layer.shadowOffset = CGSize(width: 0, height: 2)
layer.shadowRadius = 4
layer.shadowColor = UIColor.black.cgColor
layer.masksToBounds = false
}
}
请点击链接查看result