自动检测旋转时选择的集合视图单元格的中心
Automatically detect center of collection view cell selected on rotation
我在 collectionview
的 didSelectItemAt indexPath
中有以下代码
//To find center of collectionview cell
let attributes: UICollectionViewLayoutAttributes? = collectionView.layoutAttributesForItem(at: indexPath)
print("center: \((attributes?.center)!)")
当我 select 单元格处于 portrait
模式
时,我得到以下输出
center: (659.5, 200.0)
我喜欢一旋转到landscape
模式automatically
就得到下面的,也就是landscape
模式下cell的中心,没有我[=29] =]手动设置。
center: (206.0, 200.0)
有没有办法实现这一点,以便我可以将其作为 didSelectItemAt IndexPath
中的 transition.start = center
传递给过渡。
您可以在视图控制器中覆盖 viewWillTransitionToSize()
以检测旋转变化。
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
if UIDevice.currentDevice().orientation.isLandscape.boolValue {
print("Landscape")
// Get collection view center here
} else {
print("Portrait")
// Get collection view center here
}
}
实现 UIViewController
的 func willRotate(to toInterfaceOrientation: UIInterfaceOrientation, duration: TimeInterval)
方法,以便在设备方向改变时获得回调,并在其中获得所选 UICollectionViewCell
的 center
。
您可以在 UICollectionView
上使用 indexPathsForSelectedItems
来获取所选 UICollectionViewCell
的 indexPath
。
override func willRotate(to toInterfaceOrientation: UIInterfaceOrientation, duration: TimeInterval)
{
if let indexPath = self.collectionView.indexPathsForSelectedItems?.first
{
let attributes: UICollectionViewLayoutAttributes? = collectionView.layoutAttributesForItem(at: indexPath)
print("center: \((attributes?.center)!)")
}
}
我在 collectionview
didSelectItemAt indexPath
中有以下代码
//To find center of collectionview cell
let attributes: UICollectionViewLayoutAttributes? = collectionView.layoutAttributesForItem(at: indexPath)
print("center: \((attributes?.center)!)")
当我 select 单元格处于 portrait
模式
center: (659.5, 200.0)
我喜欢一旋转到landscape
模式automatically
就得到下面的,也就是landscape
模式下cell的中心,没有我[=29] =]手动设置。
center: (206.0, 200.0)
有没有办法实现这一点,以便我可以将其作为 didSelectItemAt IndexPath
中的 transition.start = center
传递给过渡。
您可以在视图控制器中覆盖 viewWillTransitionToSize()
以检测旋转变化。
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
if UIDevice.currentDevice().orientation.isLandscape.boolValue {
print("Landscape")
// Get collection view center here
} else {
print("Portrait")
// Get collection view center here
}
}
实现 UIViewController
的 func willRotate(to toInterfaceOrientation: UIInterfaceOrientation, duration: TimeInterval)
方法,以便在设备方向改变时获得回调,并在其中获得所选 UICollectionViewCell
的 center
。
您可以在 UICollectionView
上使用 indexPathsForSelectedItems
来获取所选 UICollectionViewCell
的 indexPath
。
override func willRotate(to toInterfaceOrientation: UIInterfaceOrientation, duration: TimeInterval)
{
if let indexPath = self.collectionView.indexPathsForSelectedItems?.first
{
let attributes: UICollectionViewLayoutAttributes? = collectionView.layoutAttributesForItem(at: indexPath)
print("center: \((attributes?.center)!)")
}
}