簡體   English   中英

在Swift iOS中更改方向時更改UICollectionViewCell標簽textColor

[英]Change UICollectionViewCell label textColor on orientation changes in Swift iOS

我想在設備方向更改時更改UICollectionViewCell內的UILabel的顏色。 我該如何實現。

NotificationCenter.default.addObserver(self, selector: #selector(deviceOrientationDidChange),
                                           name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)

我想讓觀察者定向更改單元格內部的通知,但我雖然不正確,因為無法刪除觀察者。 問題是,如果我在視圖控制器中觀察到方向變化,如何在通知選擇器內獲取對UICollectionView單元的引用以更改單元的標簽textColor? 這是我嘗試使用的方式:

let indexPath = IndexPath(item: 0, section: 0)
if let cell = collectionView.cellForItem(at: indexPath) as? CommentCell {
    cell.displayNameLabel.textColor = .white
    cell.commentLabel.textColor = .white
}

但是我只能訪問該indexPath的一個單元格視圖。 當我設置一個Int變量並將其值設置在cellForRowAtIndexPath內部時,什么都不會發生,因為它保存了最后一項的值。

把它放在cellForRowAt

 if(orinatedLogic)
 {
         cell.displayNameLabel.textColor = .white
         cell.commentLabel.textColor = .white
  }
  else
  {
         cell.displayNameLabel.textColor = .blue
          cell.commentLabel.textColor = .blue
  }

並在方向改變時重新加載集合

如果您使用的是Storyboard,則可以使用Vary for traits來更改標簽顏色,具體取決於方向。 在此處輸入圖片說明

有很多可能性取決於您的要求。 我假設您不想重新加載整個收藏集視圖。 但是您可以枚舉所有可見的單元格並重新加載它們,

collectionView.reloadItems(at: collectionView.indexPathsForVisibleItems)

或直接更改它們。

collectionView.visibleCells.flatMap{ $0 as? CommentCell}.forEach {
    $0.commentLabel.textColor = ...
}

對於方向更改,您只需添加

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {

    super.viewWillTransition(to: size, with: coordinator)

       collectionView.reloadItems(at: collectionView.indexPathsForVisibleItems)

}

在項目的收集視圖單元格中

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "item", for: indexPath) as! YourCellType

    cell.displayNameLabel.textColor = UIDevice.current.orientation.isPortrait ? .white : .red

    cell.commentLabel.textColor = UIDevice.current.orientation.isPortrait ? .white : .red

}

就是這樣,您做到了!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM