集合查看单元格滚动时背景更改



在我的应用程序(键盘扩展(中,我设置了一个配色方案,根据主题(亮/暗(更改背景颜色
我创建了一个集合视图,并用我的配色方案设置了它的颜色。但是,如果集合视图是可滚动的,则在我滚动它之后,一些按钮的颜色会发生变化。我该如何防止这种情况发生
这种情况仅在暗模式中发生

这就是我如何设置我的配色方案

enum Scheme {
case dark
case light
}
struct Colors {

let keysDefaultColor: UIColor
let keysHighlightColor: UIColor

let grayKeysDefaultColor: UIColor
let grayKeysHighlightColor: UIColor

let buttonTextColor: UIColor

init(colorScheme: Scheme) {
switch colorScheme {
case .light:

keysDefaultColor = UIColor.white
keysHighlightColor = UIColor.lightGray.withAlphaComponent(0.6)

grayKeysDefaultColor = UIColor.lightGray.withAlphaComponent(0.6)
grayKeysHighlightColor = UIColor.white

buttonTextColor = .black

case .dark:

keysDefaultColor = UIColor.gray.withAlphaComponent(0.5)
keysHighlightColor = UIColor.lightGray.withAlphaComponent(0.5)

grayKeysDefaultColor =  UIColor.darkGray.withAlphaComponent(0.5)
grayKeysHighlightColor = UIColor.gray.withAlphaComponent(0.5)

buttonTextColor = .white

}
}
}

然后我有一个集合视图,我为单元格创建了一个自定义类。在我声明并设置集合视图(可滚动(后,我创建了以下函数来设置其颜色:

func setColorScheme(_ colorScheme: Scheme) {
let colorScheme =  Colors(colorScheme: colorScheme)

func setToRootView(view: UIView) {
if let cell = view as? CustomCells {
cell.label.textColor = colorScheme.buttonTextColor

cell.defaultColor = colorScheme.keysDefaultColor
cell.highlighColor = colorScheme.keysHighlightColor

cell.setBackground() //This sets highlight background on tap and default for normal state
return
}
guard view.subviews.count > 0 else {
return
}
view.subviews.forEach(setToRootView(view:))
}
setToRootView(view: self)

}

我在视图的init中调用这个函数,在这里我放置了集合视图和键盘视图控制器:

override func textDidChange(_ textInput: UITextInput?) {
// The app has just changed the document's contents, the document context has been updated.
let colorScheme:  Scheme
let proxy = self.textDocumentProxy
if proxy.keyboardAppearance == UIKeyboardAppearance.dark {
colorScheme = .dark
} else {
colorScheme = .light
}

myView.setColorScheme(colorScheme)
}

商品单元格位于:

let cell = myCollection.dequeueReusableCell(withReuseIdentifier: "keyboardCellsId", for: indexPath) as! CustomCells
cell.label.text = String("abc")
return cell

所以我想我错过了什么。我知道我没有发布完整的代码,但这是因为我不想让这个问题太重,如果你需要更多,请告诉我。

您可以共享您的collectionViewcellForItem委托方法吗?

我认为您可能需要设置集合中单元格和按钮的颜色查看cellForItem委托方法

它第一次正确加载的原因是,所有可见单元格都设置为正确的颜色,但在显示新单元格时,按钮上的颜色可能无法正确设置

最新更新