`setCollectionViewLayout` 动画在更改 collection 视图框架时中断
`setCollectionViewLayout` animation broken when also changing collection view frame
我正在尝试在水平film-strip布局和垂直堆栈之间转换我的collection视图]布局。
Horizontal film strip
Vertical/expanded stack
这是我目前正在做的事情:
- 使用
setCollectionViewLayout(_:animated:completion:)
在水平和垂直滚动方向之间转换
- 更改 collection 视图的高度限制,以及
UIView.animate
和 self.view.layoutIfNeeded()
从film-strip到垂直堆叠的动画没问题。但是,从垂直堆栈到 film-strip 的动画已损坏。这是它的样子:
如果我默认设置 collectionViewHeightConstraint
300,并删除这些行:
collectionViewHeightConstraint.constant = 300
collectionViewHeightConstraint.constant = 50
...过渡动画两种方式都很好。但是,间距过大,我希望 film-strip 布局仅在 1 行中。
如何使动画在双向都流畅?这是我的代码 (link to the demo project):
class ViewController: UIViewController {
var isExpanded = false
var verticalFlowLayout = UICollectionViewFlowLayout()
var horizontalFlowLayout = UICollectionViewFlowLayout()
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var collectionViewHeightConstraint: NSLayoutConstraint!
@IBAction func toggleExpandPressed(_ sender: Any) {
isExpanded.toggle()
if isExpanded {
collectionView.setCollectionViewLayout(verticalFlowLayout, animated: true) /// set vertical scroll
collectionViewHeightConstraint.constant = 300 /// make collection view height taller
} else {
collectionView.setCollectionViewLayout(horizontalFlowLayout, animated: true) /// set horizontal scroll
collectionViewHeightConstraint.constant = 50 /// make collection view height shorter
}
/// animate the collection view's height
UIView.animate(withDuration: 1) {
self.view.layoutIfNeeded()
}
/// Bonus points:
/// This makes the animation way more worse, but I would like to be able to scroll to a specific IndexPath during the transition.
// collectionView.scrollToItem(at: IndexPath(item: 9, section: 0), at: .bottom, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
verticalFlowLayout.scrollDirection = .vertical
horizontalFlowLayout.scrollDirection = .horizontal
collectionView.collectionViewLayout = horizontalFlowLayout
collectionView.dataSource = self
collectionView.delegate = self
}
}
extension ViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
/// if expanded, cells should be full-width
/// if not expanded, cells should have a width of 50
return isExpanded ? CGSize(width: collectionView.frame.width, height: 50) : CGSize(width: 100, height: 50)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0 /// no spacing needed for now
}
}
/// sample data source
extension ViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ID", for: indexPath)
cell.contentView.layer.borderWidth = 5
cell.contentView.layer.borderColor = UIColor.red.cgColor
return cell
}
}
问题是动画改变布局和改变高度相互碰撞,因为动画的持续时间不同。我建议进行以下更改
UIView.animate(withDuration: self.isExpanded ? 0.3 : 0.5, delay: 0.0, options: self.isExpanded ? .curveEaseIn : .curveEaseOut) {
if self.isExpanded {
self.collectionView.setCollectionViewLayout(self.verticalFlowLayout, animated: false) /// set vertical scroll
self.collectionViewHeightConstraint.constant = 300 /// make collection view height taller
} else{
self.collectionView.setCollectionViewLayout(self.horizontalFlowLayout, animated: false) /// set horizontal scroll
self.collectionViewHeightConstraint.constant = 50 /// make collection view height shorter
}
self.view.layoutIfNeeded()
} completion: { (completed) in
self.collectionView.reloadData()
}
您可以使用此代码修复动画。此外,设置延迟 self.collectionView.scrollToItem
(设置延迟值与动画持续时间相同)
@IBAction func toggleExpandPressed(_ sender: Any) {
isExpanded.toggle()
if isExpanded {
collectionView.setCollectionViewLayout(verticalFlowLayout, animated: true) /// set vertical scroll
collectionViewHeightConstraint.constant = 300 /// make collection view height taller
UIView.animate(withDuration: 1) {
self.view.layoutIfNeeded()
}
} else {
collectionViewHeightConstraint.constant = 50 /// make collection view height shorter
UIView.animate(withDuration: 1) { [self] in
self.view.layoutIfNeeded()
collectionView.setCollectionViewLayout(horizontalFlowLayout, animated: false) /// set horizontal scroll
}
}
/// Bonus points:
/// This makes the animation way more worse, but I would like to be able to scroll to a specific IndexPath during the transition.
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.collectionView.scrollToItem(at: IndexPath(item: self.isExpanded ? 9 : 5, section: 0), at: self.isExpanded ? .centeredVertically : .centeredHorizontally, animated: true)
}
}
我使用自定义 UICollectionViewFlowLayout
class (link to demo repo) 让它工作。中心单元甚至在两种布局中都居中(这实际上是我问题中“奖励积分”部分的确切目的)!
这是我的视图控制器。我现在使用自定义闭包 sizeForListItemAt
和 sizeForStripItemAt
.
,而不是遵循 UICollectionViewDelegateFlowLayout
class ViewController: UIViewController {
var isExpanded = false
lazy var listLayout = FlowLayout(layoutType: .list)
lazy var stripLayout = FlowLayout(layoutType: .strip)
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var collectionViewHeightConstraint: NSLayoutConstraint!
@IBAction func toggleExpandPressed(_ sender: Any) {
isExpanded.toggle()
if isExpanded {
collectionView.setCollectionViewLayout(listLayout, animated: true)
collectionViewHeightConstraint.constant = 300
} else {
collectionView.setCollectionViewLayout(stripLayout, animated: true)
collectionViewHeightConstraint.constant = 60
}
UIView.animate(withDuration: 0.6) {
self.view.layoutIfNeeded()
}
}
override func viewDidLoad() {
super.viewDidLoad()
collectionView.collectionViewLayout = stripLayout
collectionView.dataSource = self
/// use these instead of `UICollectionViewDelegateFlowLayout`
listLayout.sizeForListItemAt = { [weak self] indexPath in
return CGSize(width: self?.collectionView.frame.width ?? 100, height: 50)
}
stripLayout.sizeForStripItemAt = { indexPath in
return CGSize(width: 100, height: 50)
}
}
}
/// sample data source
extension ViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ID", for: indexPath)
cell.contentView.layer.borderWidth = 5
cell.contentView.layer.borderColor = UIColor.red.cgColor
return cell
}
}
那么,这是我的习惯UICollectionViewFlowLayout
class。在prepare
里面,我手动计算并设置了每个cell的frame。我不确定为什么会这样,但系统现在能够找出哪些单元格等于哪些单元格,甚至跨越多个 FlowLayout
s(listLayout
和 stripLayout
)。
enum LayoutType {
case list
case strip
}
class FlowLayout: UICollectionViewFlowLayout {
var layoutType: LayoutType
var sizeForListItemAt: ((IndexPath) -> CGSize)? /// get size for list item
var sizeForStripItemAt: ((IndexPath) -> CGSize)? /// get size for strip item
var layoutAttributes = [UICollectionViewLayoutAttributes]() /// store the frame of each item
var contentSize = CGSize.zero /// the scrollable content size of the collection view
override var collectionViewContentSize: CGSize { return contentSize } /// pass scrollable content size back to the collection view
override func prepare() { /// configure the cells' frames
super.prepare()
guard let collectionView = collectionView else { return }
let itemCount = collectionView.numberOfItems(inSection: 0) /// I only have 1 section
if layoutType == .list {
var y: CGFloat = 0 /// y position of each cell, start at 0
for itemIndex in 0..<itemCount {
let indexPath = IndexPath(item: itemIndex, section: 0)
let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
attributes.frame = CGRect(
x: 0,
y: y,
width: sizeForListItemAt?(indexPath).width ?? 0,
height: sizeForListItemAt?(indexPath).height ?? 0
)
layoutAttributes.append(attributes)
y += attributes.frame.height /// add height to y position, so next cell becomes offset
} /// use first item's width
contentSize = CGSize(width: sizeForStripItemAt?(IndexPath(item: 0, section: 0)).width ?? 0, height: y)
} else {
var x: CGFloat = 0 /// z position of each cell, start at 0
for itemIndex in 0..<itemCount {
let indexPath = IndexPath(item: itemIndex, section: 0)
let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
attributes.frame = CGRect(
x: x,
y: 0,
width: sizeForStripItemAt?(indexPath).width ?? 0,
height: sizeForStripItemAt?(indexPath).height ?? 0
)
layoutAttributes.append(attributes)
x += attributes.frame.width /// add width to z position, so next cell becomes offset
} /// use first item's height
contentSize = CGSize(width: x, height: sizeForStripItemAt?(IndexPath(item: 0, section: 0)).height ?? 0)
}
}
/// pass attributes to the collection view flow layout
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
return layoutAttributes[indexPath.item]
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
return layoutAttributes.filter { rect.intersects([=11=].frame) }
}
/// initialize with a layout
init(layoutType: LayoutType) {
self.layoutType = layoutType
super.init()
}
/// boilerplate code
required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { return true }
override func invalidationContext(forBoundsChange newBounds: CGRect) -> UICollectionViewLayoutInvalidationContext {
let context = super.invalidationContext(forBoundsChange: newBounds) as! UICollectionViewFlowLayoutInvalidationContext
context.invalidateFlowLayoutDelegateMetrics = newBounds.size != collectionView?.bounds.size
return context
}
}
感谢this amazing article的大力帮助。
我正在尝试在水平film-strip布局和垂直堆栈之间转换我的collection视图]布局。
Horizontal film strip | Vertical/expanded stack |
---|---|
这是我目前正在做的事情:
- 使用
setCollectionViewLayout(_:animated:completion:)
在水平和垂直滚动方向之间转换 - 更改 collection 视图的高度限制,以及
UIView.animate
和self.view.layoutIfNeeded()
从film-strip到垂直堆叠的动画没问题。但是,从垂直堆栈到 film-strip 的动画已损坏。这是它的样子:
如果我默认设置 collectionViewHeightConstraint
300,并删除这些行:
collectionViewHeightConstraint.constant = 300
collectionViewHeightConstraint.constant = 50
...过渡动画两种方式都很好。但是,间距过大,我希望 film-strip 布局仅在 1 行中。
如何使动画在双向都流畅?这是我的代码 (link to the demo project):
class ViewController: UIViewController {
var isExpanded = false
var verticalFlowLayout = UICollectionViewFlowLayout()
var horizontalFlowLayout = UICollectionViewFlowLayout()
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var collectionViewHeightConstraint: NSLayoutConstraint!
@IBAction func toggleExpandPressed(_ sender: Any) {
isExpanded.toggle()
if isExpanded {
collectionView.setCollectionViewLayout(verticalFlowLayout, animated: true) /// set vertical scroll
collectionViewHeightConstraint.constant = 300 /// make collection view height taller
} else {
collectionView.setCollectionViewLayout(horizontalFlowLayout, animated: true) /// set horizontal scroll
collectionViewHeightConstraint.constant = 50 /// make collection view height shorter
}
/// animate the collection view's height
UIView.animate(withDuration: 1) {
self.view.layoutIfNeeded()
}
/// Bonus points:
/// This makes the animation way more worse, but I would like to be able to scroll to a specific IndexPath during the transition.
// collectionView.scrollToItem(at: IndexPath(item: 9, section: 0), at: .bottom, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
verticalFlowLayout.scrollDirection = .vertical
horizontalFlowLayout.scrollDirection = .horizontal
collectionView.collectionViewLayout = horizontalFlowLayout
collectionView.dataSource = self
collectionView.delegate = self
}
}
extension ViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
/// if expanded, cells should be full-width
/// if not expanded, cells should have a width of 50
return isExpanded ? CGSize(width: collectionView.frame.width, height: 50) : CGSize(width: 100, height: 50)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0 /// no spacing needed for now
}
}
/// sample data source
extension ViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ID", for: indexPath)
cell.contentView.layer.borderWidth = 5
cell.contentView.layer.borderColor = UIColor.red.cgColor
return cell
}
}
问题是动画改变布局和改变高度相互碰撞,因为动画的持续时间不同。我建议进行以下更改
UIView.animate(withDuration: self.isExpanded ? 0.3 : 0.5, delay: 0.0, options: self.isExpanded ? .curveEaseIn : .curveEaseOut) {
if self.isExpanded {
self.collectionView.setCollectionViewLayout(self.verticalFlowLayout, animated: false) /// set vertical scroll
self.collectionViewHeightConstraint.constant = 300 /// make collection view height taller
} else{
self.collectionView.setCollectionViewLayout(self.horizontalFlowLayout, animated: false) /// set horizontal scroll
self.collectionViewHeightConstraint.constant = 50 /// make collection view height shorter
}
self.view.layoutIfNeeded()
} completion: { (completed) in
self.collectionView.reloadData()
}
您可以使用此代码修复动画。此外,设置延迟 self.collectionView.scrollToItem
(设置延迟值与动画持续时间相同)
@IBAction func toggleExpandPressed(_ sender: Any) {
isExpanded.toggle()
if isExpanded {
collectionView.setCollectionViewLayout(verticalFlowLayout, animated: true) /// set vertical scroll
collectionViewHeightConstraint.constant = 300 /// make collection view height taller
UIView.animate(withDuration: 1) {
self.view.layoutIfNeeded()
}
} else {
collectionViewHeightConstraint.constant = 50 /// make collection view height shorter
UIView.animate(withDuration: 1) { [self] in
self.view.layoutIfNeeded()
collectionView.setCollectionViewLayout(horizontalFlowLayout, animated: false) /// set horizontal scroll
}
}
/// Bonus points:
/// This makes the animation way more worse, but I would like to be able to scroll to a specific IndexPath during the transition.
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.collectionView.scrollToItem(at: IndexPath(item: self.isExpanded ? 9 : 5, section: 0), at: self.isExpanded ? .centeredVertically : .centeredHorizontally, animated: true)
}
}
我使用自定义 UICollectionViewFlowLayout
class (link to demo repo) 让它工作。中心单元甚至在两种布局中都居中(这实际上是我问题中“奖励积分”部分的确切目的)!
这是我的视图控制器。我现在使用自定义闭包 sizeForListItemAt
和 sizeForStripItemAt
.
UICollectionViewDelegateFlowLayout
class ViewController: UIViewController {
var isExpanded = false
lazy var listLayout = FlowLayout(layoutType: .list)
lazy var stripLayout = FlowLayout(layoutType: .strip)
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var collectionViewHeightConstraint: NSLayoutConstraint!
@IBAction func toggleExpandPressed(_ sender: Any) {
isExpanded.toggle()
if isExpanded {
collectionView.setCollectionViewLayout(listLayout, animated: true)
collectionViewHeightConstraint.constant = 300
} else {
collectionView.setCollectionViewLayout(stripLayout, animated: true)
collectionViewHeightConstraint.constant = 60
}
UIView.animate(withDuration: 0.6) {
self.view.layoutIfNeeded()
}
}
override func viewDidLoad() {
super.viewDidLoad()
collectionView.collectionViewLayout = stripLayout
collectionView.dataSource = self
/// use these instead of `UICollectionViewDelegateFlowLayout`
listLayout.sizeForListItemAt = { [weak self] indexPath in
return CGSize(width: self?.collectionView.frame.width ?? 100, height: 50)
}
stripLayout.sizeForStripItemAt = { indexPath in
return CGSize(width: 100, height: 50)
}
}
}
/// sample data source
extension ViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ID", for: indexPath)
cell.contentView.layer.borderWidth = 5
cell.contentView.layer.borderColor = UIColor.red.cgColor
return cell
}
}
那么,这是我的习惯UICollectionViewFlowLayout
class。在prepare
里面,我手动计算并设置了每个cell的frame。我不确定为什么会这样,但系统现在能够找出哪些单元格等于哪些单元格,甚至跨越多个 FlowLayout
s(listLayout
和 stripLayout
)。
enum LayoutType {
case list
case strip
}
class FlowLayout: UICollectionViewFlowLayout {
var layoutType: LayoutType
var sizeForListItemAt: ((IndexPath) -> CGSize)? /// get size for list item
var sizeForStripItemAt: ((IndexPath) -> CGSize)? /// get size for strip item
var layoutAttributes = [UICollectionViewLayoutAttributes]() /// store the frame of each item
var contentSize = CGSize.zero /// the scrollable content size of the collection view
override var collectionViewContentSize: CGSize { return contentSize } /// pass scrollable content size back to the collection view
override func prepare() { /// configure the cells' frames
super.prepare()
guard let collectionView = collectionView else { return }
let itemCount = collectionView.numberOfItems(inSection: 0) /// I only have 1 section
if layoutType == .list {
var y: CGFloat = 0 /// y position of each cell, start at 0
for itemIndex in 0..<itemCount {
let indexPath = IndexPath(item: itemIndex, section: 0)
let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
attributes.frame = CGRect(
x: 0,
y: y,
width: sizeForListItemAt?(indexPath).width ?? 0,
height: sizeForListItemAt?(indexPath).height ?? 0
)
layoutAttributes.append(attributes)
y += attributes.frame.height /// add height to y position, so next cell becomes offset
} /// use first item's width
contentSize = CGSize(width: sizeForStripItemAt?(IndexPath(item: 0, section: 0)).width ?? 0, height: y)
} else {
var x: CGFloat = 0 /// z position of each cell, start at 0
for itemIndex in 0..<itemCount {
let indexPath = IndexPath(item: itemIndex, section: 0)
let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
attributes.frame = CGRect(
x: x,
y: 0,
width: sizeForStripItemAt?(indexPath).width ?? 0,
height: sizeForStripItemAt?(indexPath).height ?? 0
)
layoutAttributes.append(attributes)
x += attributes.frame.width /// add width to z position, so next cell becomes offset
} /// use first item's height
contentSize = CGSize(width: x, height: sizeForStripItemAt?(IndexPath(item: 0, section: 0)).height ?? 0)
}
}
/// pass attributes to the collection view flow layout
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
return layoutAttributes[indexPath.item]
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
return layoutAttributes.filter { rect.intersects([=11=].frame) }
}
/// initialize with a layout
init(layoutType: LayoutType) {
self.layoutType = layoutType
super.init()
}
/// boilerplate code
required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { return true }
override func invalidationContext(forBoundsChange newBounds: CGRect) -> UICollectionViewLayoutInvalidationContext {
let context = super.invalidationContext(forBoundsChange: newBounds) as! UICollectionViewFlowLayoutInvalidationContext
context.invalidateFlowLayoutDelegateMetrics = newBounds.size != collectionView?.bounds.size
return context
}
}
感谢this amazing article的大力帮助。