簡體   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