检测旋转时的字体更改

时间:2017-11-05 06:07:37

标签: ios swift xcode

我有以下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字体。我该如何纠正这个问题?

1 个答案:

答案 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()
}