我有以下viewcontroller
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
@IBOutlet weak var collectionView: UICollectionView!
var dogs = ["Dog1", "Dog2","Dog3"]
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dogs.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CustomCell", for: indexPath) as! CustomCell
cell.testLabel.text = dogs[indexPath.row]
return cell
}
}
以及以下CustomCell
class CustomCell: UICollectionViewCell {
@IBOutlet weak var testLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
if (UIDevice.current.orientation == UIDeviceOrientation.portrait)
{
testLabel.font = UIFont(name: "HelveticaNeue-Bold", size: 10)
}
else
{
testLabel.font = UIFont(name: "HelveticaNeue-Italic", size: 25)
}
}
}
我在访问viewcontroller
时最初观察字体更改,但在旋转设备时没有观察到。例如,如果设备位于portrait
并且我访问viewcontroller
,我收到了正确的字体但是如果我将其更改为landscape
,它仍会显示portrait
字体。
同样,如果我转到另一个viewcontroller
并访问present
中的viewcontroller
landscape
,则会显示正确的字体,当我将方向更改为{{1它仍然记住portratit
字体。我该如何纠正这个问题?
答案 0 :(得分:3)
要解决您的问题,您应该在testLabel
中设置font
cellForItemAt
,只需在轮换更改时,您只需要为您的collectionView调用reloadData
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CustomCell", for: indexPath) as! CustomCell
cell.testLabel.text = dogs[indexPath.row]
if (UIDevice.current.orientation == UIDeviceOrientation.portrait)
{
cell.testLabel.font = UIFont(name: "HelveticaNeue-Bold", size: 10)
}
else
{
cell.testLabel.font = UIFont(name: "HelveticaNeue-Italic", size: 25)
}
return cell
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
YOUR_COLLECTION_VIEW.reloadData()
}