繁体   English   中英

检测旋转时的字体更改

[英]Detect font changes on rotation

我有以下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并在landscape访问present viewcontroller ,它显示正确的字体,当我将方向更改为portratit ,它仍然记住landscape字体。 我该如何纠正这个?

要解决您的问题,您应该在cellForItemAt设置testLabel font ,并且只需在旋转更改时,您只需要为您的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()
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM