【发布时间】:2020-10-19 02:40:58
【问题描述】:
我正在使用 UICollectionViewController 来显示 UICollectionViewCell 的集合,用户可以在 ios 13、swift 5 和 UIKit 之间滑动。如果用户改变了方向,我最终想重新绘制单元格。在我的控制器中,我注意到这段代码会在方向更改时执行:
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! MyCell
return cell
}
在 MyCell 中,我使用此代码进行监控,然后重新初始化布局:
override init(frame: CGRect) {
super.init(frame: frame)
setLayout()
print("### orientation:: \(UIDevice.current.orientation.isLandscape) ")
}
结果:这个方法被调用了 2 次。当应用程序启动时,以及当我从纵向更改为横向时。任何后续更改,不要调用它。我怀疑这很好,因为可能两个版本都被缓存了(风景和肖像)。如果我根据 UIDevice.current.orientation.isLandscape 标志向 setLayout() 方法添加代码,则在执行时不会发生任何变化。注意:UIDevice.current.orientation.isLandscape 的实际结果是正确的。
这是我的 setLayout() 方法中的一个示例:
let topImageViewContainer = UIView();
topImageViewContainer.translatesAutoresizingMaskIntoConstraints = false
topImageViewContainer.backgroundColor = .yellow
addSubview(topImageViewContainer)
NSLayoutConstraint.activate([
topImageViewContainer.topAnchor.constraint(equalTo: topAnchor),
topImageViewContainer.leftAnchor.constraint(equalTo: leftAnchor),
topImageViewContainer.rightAnchor.constraint(equalTo: rightAnchor),
topImageViewContainer.heightAnchor.constraint(equalTo: heightAnchor, multiplier: 0.5)
])
if (UIDevice.current.orientation.isLandscape) {
let imageView = UIImageView(image: UIImage(named: "photo_a"))
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFit
topImageViewContainer.addSubview(imageView)
} else {
let imageView = UIImageView(image: UIImage(named: "photo_b"))
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFit
topImageViewContainer.addSubview(imageView)
}
在上面的示例中,带有“photo_a”的代码正在执行,但 ui 仍然显示 photo_b。我怀疑我做错了什么,我需要以某种方式迁移到此处提到的“自适应布局”:Different layouts in portrait and landscape mode。但是,我不确定如何将一些“viewWillTransition*”函数挂接到具有 UIView 的 UICollectionViewCell。
如何调整实现 UICollectionViewCell 的 MyCell 类,以允许在用户以 Swift 预期的方式从横向更改为纵向时更新单元格?
【问题讨论】:
-
实现
layoutSubviews并查看自上次以来我们是否因轮换而被调用。 “以斯威夫特的预期方式?”无关紧要。无论您使用哪种语言,Cocoa 都是 Cocoa。 -
@matt 我的意思是“Swift 预期的方式”,更多的是“我不是为了让它工作而修改代码,而是遵循最佳实践。&& layoutSubviews 在旋转更改时执行多次。