I have the following 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
}
}
and the following 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)
}
}
}
I am observing font changes initially when the viewcontroller
is accessed but not when I am rotating the device.For example, if the device is in portrait
and I access the viewcontroller
, I am getting the correct font but if I change it to landscape
, it is still showing portrait
font.
Similarly, if I go to another viewcontroller
and access the present
viewcontroller
in landscape
, it is showing correct font and when I change the orientation to portratit
, it is still remembering the landscape
font. How do I rectify this?
To solve your problem, you should set testLabel
font
in cellForItemAt
and simply when rotation changes, you just need call reloadData
for your collectionView
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()
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.