如何根据设备主题更改collectionview单元格颜色(按照我的配色方案)

     2023-03-14     230

关键词:

【中文标题】如何根据设备主题更改collectionview单元格颜色(按照我的配色方案)【英文标题】:How to change collectionview cells color based on device theme (following my color scheme) 【发布时间】:2020-10-28 15:27:08 【问题描述】:

概述:

我正在使用集合视图构建键盘扩展。我希望单元格根据设备主题(亮/暗)更改颜色。目前,当我为我的 collectionview 单元格设置配色方案时,它们不起作用。我正在用“///”注释标记我的代码有问题的部分。

资源:

我找到了this RayWenderlich project,我喜欢他们处理颜色变化的方式,所以我复制了它。

我的代码:

我有 3 个课程:

    键盘视图控制器 包含键盘按钮的自定义视图 自定义 collectionview 单元格

CollectionView 单元格

class KeyboardKeys: UICollectionViewCell 
    
    var defaultColor = UIColor.white
    var highlighColor = UIColor.lightGray.withAlphaComponent(0.6)
    
    let label: UILabel = 
        let iv = UILabel()
        iv.translatesAutoresizingMaskIntoConstraints = false
        iv.contentMode =  .scaleAspectFit
        iv.font = UIFont.systemFont(ofSize: 20)
        iv.clipsToBounds = true
        iv.numberOfLines = 1
        iv.textAlignment = .center
        
        return iv
    ()

    override init(frame: CGRect) 
        super.init(frame: .zero)
        commonInit()
    
    
    required init?(coder aDecoder: NSCoder) 
        super.init(coder: aDecoder)
        commonInit()
    
    
    func commonInit() 
        contentView.addSubview(label)
        label.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
        label.leftAnchor.constraint(equalTo: contentView.leftAnchor).isActive = true
        label.rightAnchor.constraint(equalTo: contentView.rightAnchor).isActive = true
        label.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true   
    
    
    override func layoutSubviews() 
        super.layoutSubviews()
            backgroundColor = isHighlighted ? highlighColor : defaultColor  
       

自定义视图

class lettersKeyboard: UIView, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout
var keyView: UICollectionView!
 let letters = ["q", "w", "e", "r", "t", "y", "u", "i", "o", "p"]
 override init(frame: CGRect) 
        super.init(frame: frame)
        commonInit()
    
    
    required init?(coder aDecoder: NSCoder) 
        super.init(coder: aDecoder)
        commonInit()
        
    
    
    private func commonInit()
//If you find some errors it's because this is way different in my code. This is just a regulare  collection view anyway

    let layout = UICollectionViewFlowLayout()
    layout.scrollDirection = .vertical
        
    keyView = UICollectionView(frame: CGRect(x: 0.0, y: 0.0 , width: frame.width, height: 280), collectionViewLayout: layout)
    keyView.setCollectionViewLayout(layout, animated: true)
    keyView.isScrollEnabled = false
    keyView.register(KeyboardKeys.self, forCellWithReuseIdentifier: "collectionCellId")
    keyView.delegate = self
    keyView.dataSource = self
    addSubview(keyView)


    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int 
        10
    
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell 
        let cell = keyView.dequeueReusableCell(withReuseIdentifier: "collectionCellId", for: indexPath) as! KeyboardKeys
        cell.label.text = letters[indexPath.row]
        return cell
    
    ///I guess something is wrong here 
    func setColorScheme(_ colorScheme: ColorScheme) 
      let colorScheme = CColors(colorScheme: colorScheme)
     
      for view in subviews 
        if let cell = view as? KeyboardKeys 
            cell.tintColor = colorScheme.buttonTextColor
            cell.defaultColor = colorScheme.keysDefaultColor
            cell.highlighColor = colorScheme.keysHighlightColor
      
      
    
    


配色方案结构

enum ColorScheme 
    case dark
    case light


struct CColors 
    
    let keysDefaultColor: UIColor
    let keysHighlightColor: UIColor
    
    let buttonTextColor: UIColor
   
    
    init(colorScheme: ColorScheme) 
        switch colorScheme 
        case .light:
           
            keysDefaultColor = .systemRed
                //UIColor.white
            keysHighlightColor = UIColor.lightGray.withAlphaComponent(0.6)
         
            buttonTextColor = .black
           
        case .dark:
            
            keysDefaultColor = .systemBlue
                // UIColor.gray.withAlphaComponent(0.5)
            keysHighlightColor = UIColor.lightGray.withAlphaComponent(0.5)
            
            buttonTextColor = .white  
        
    

键盘视图控制器

class KeyboardViewController: UIInputViewController 
var letters : lettersKeyboard = 
      
        let m = lettersKeyboard(frame: .zero)
            m.translatesAutoresizingMaskIntoConstraints = false

            m.backgroundColor = .clear
            return m
        
()
override func viewDidLoad() 
        super.viewDidLoad()
 
        view.addSubview(letters)
   
        letters.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        letters.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
        letters.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
        letters.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true

//The rest is the default inputvc stuff 

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

问题:

我不知道我做错了什么,因为我的代码适用于除了 collectionview 单元格之外的所有内容。我想存在另一种做这些事情的方法。那么如何根据我的配色方案根据设备的主题更改我的 collectionView 单元格的颜色?

【问题讨论】:

【参考方案1】:

您确实应该重新加载集合视图,而不是试图找到作为键的子视图并更新它们。

将 colorScheme 模型传递给每个单元格,并在重新加载时设置颜色。

【讨论】:

是的,我认为@Jay 是对的。您需要重新加载集合视图(您的自定义键盘),并为简单起见将颜色作为计算属性,通过检查主题来给出结果。【参考方案2】:

一个非常善良的人帮助我找到了这个解决方案。这里的问题是我忘记了视图的层次结构。

CollectionView 单元格

 override func layoutSubviews() 
        super.layoutSubviews()
           setupBackGround()
     
func setupBackGround()
backgroundColor = isHighlighted ? highlighColor : defaultColor

键盘视图控制器


func setColorScheme(_ colorScheme: ColorScheme) 
      let colorScheme = CColors(colorScheme: colorScheme)
     
      for view in subviews 
         func setToRootView(view: UIView) 
                if let cell = view as? KeyboardKeys 
                    cell.tintColor = colorScheme.buttonTextColor
                    cell.defaultColor = colorScheme.keysDefaultColor
                    cell.highlighColor = colorScheme.keysHighlightColor
                    cell.setBackground()
                    return
                
                guard view.subviews.count > 0 else 
                    return
                
                view.subviews.forEach(setToRootView(view:))
            
            setToRootView(view: self)
        

【讨论】:

如何根据主题更改状态栏/导航栏颜色/亮度?

】如何根据主题更改状态栏/导航栏颜色/亮度?【英文标题】:Howtochangestatusbar/navigationbarcolor/brightnesswithrespectivetotheme?【发布时间】:2022-01-2002:58:27【问题描述】:使用Getx进行主题化,但在根据浅色/深色主题更改状态栏图标亮... 查看详情

如何在 Flutter 中通过更改主题来更改文本颜色

】如何在Flutter中通过更改主题来更改文本颜色【英文标题】:HowtochangetheTextcolorwithchangeofthemeinFlutter【发布时间】:2020-03-1912:22:57【问题描述】:我正在开发一个应用程序,它会根据系统的主题更改其主题数据,即如果用户为他... 查看详情

CollectionView -> 根据是不是登录更改流程

】CollectionView->根据是不是登录更改流程【英文标题】:CollectionView->changingflowbasedonifloggedinCollectionView->根据是否登录更改流程【发布时间】:2013-08-0100:36:40【问题描述】:我有一个使用StoryBoard、CollectionViews和NavigationControll... 查看详情

如何根据深色/浅色主题更改布局背景图像?

】如何根据深色/浅色主题更改布局背景图像?【英文标题】:HowtochangealayoutbackgroundimagedependingonDark/Lighttheme?【发布时间】:2021-12-3014:04:29【问题描述】:我有两张图片。我想这样做:当用户打开具有Light主题的应用程序时-第一... 查看详情

根据 CollectionView 中的选择更改 ImageView

】根据CollectionView中的选择更改ImageView【英文标题】:ChangingImageViewBasedonSelectionInACollectionView【发布时间】:2017-08-1621:27:05【问题描述】:我目前有一个CollectionView和1个可重复使用的单元格,其中填满了ImageView。这个单元格被使... 查看详情

如何在 Qt C++ 中根据主题更改图标?如果可用的主题是深色或浅色

】如何在QtC++中根据主题更改图标?如果可用的主题是深色或浅色【英文标题】:HowtochangeiconsbasedonthemeinQtC++?Ifavailablethemesaredarkorlight【发布时间】:2014-11-0808:40:23【问题描述】:我有一个基于Qt的文本编辑器程序。它的默认主题... 查看详情

Flutter 如何听设备暗色主题瞬间变化

】Flutter如何听设备暗色主题瞬间变化【英文标题】:Flutterhowlolistendevicedarkthemechangeinstantly【发布时间】:2021-07-1219:45:52【问题描述】:我的Flutter应用程序不会在深色主题功能下听取用户的偏好变化。我需要硬重启我的应用以反... 查看详情

如何根据设备方向更改堆栈视图方向?

】如何根据设备方向更改堆栈视图方向?【英文标题】:Howtochangestackvieworientationdependingondeviceorientation?【发布时间】:2021-03-2120:05:11【问题描述】:对于尺寸等级为常规-常规的Ipad,适用于纵向/横向两种设备方向,我想强制堆栈... 查看详情

如何根据设置的主题更改颤动中的状态栏图标和文本颜色?

】如何根据设置的主题更改颤动中的状态栏图标和文本颜色?【英文标题】:Howtochangestatusbariconandtextcolorinflutterbasedonthemebeenset?【发布时间】:2020-01-1914:05:23【问题描述】:如何在没有任何第三方插件的情况下更新状态栏图标的... 查看详情

设备方向更改时如何更改 UiCollectionView 单元格大小?

】设备方向更改时如何更改UiCollectionView单元格大小?【英文标题】:HowtochangeUiCollectionViewcellsizewhendeviceorientationchanges?【发布时间】:2016-04-1205:37:24【问题描述】:我正在使用UICollectionView并使用以下方法设置单元格的大小:funcco... 查看详情

如何根据设备的分辨率更改样式?

】如何根据设备的分辨率更改样式?【英文标题】:HowdoIgetthestyletochangebasedontheresolutionofthedevice?【发布时间】:2021-12-1806:00:36【问题描述】:我一直在处理我的styles.xml文件,以便根据加载应用程序的分辨率使按钮的文本更改颜... 查看详情

如何使选定的单选按钮根据另一个单选按钮更改另一个状态来更改一个状态?

】如何使选定的单选按钮根据另一个单选按钮更改另一个状态来更改一个状态?【英文标题】:HowdoImakeaselectedradiobuttonchangeonepieceofstatebaseduponanotherradiobuttonchanginganotherpieceofstate?【发布时间】:2020-05-2923:19:54【问题描述】:我正... 查看详情

合成:如何根据单选按钮中的选定选项动态更改画布新图纸?

】合成:如何根据单选按钮中的选定选项动态更改画布新图纸?【英文标题】:Compositing:howtochangecanvasnewdrawingsdynamicallybasedonselectedoptionfromradiobutton?【发布时间】:2015-11-2608:01:11【问题描述】:几个月前我有一个relatedquestion,关... 查看详情

有没有办法根据应用程序主题更改初始屏幕颜色?

...主题?有点像当系统主题设置为深色时,WhatsApp启动画面如何在深色主题中加载。深色和浅色What 查看详情

根据数据库更改单选按钮操作

...onasperdatabase【发布时间】:2017-10-2804:36:36【问题描述】:如何根据从数据库中获取值来更改单选按钮的操作。如果我从数据库中获取性别值是男性,则应该选择男性,如果我将获得女性单选按钮必须检查为女性。【问题讨论】:... 查看详情

如何根据内容设置collectionview单元格宽度?

】如何根据内容设置collectionview单元格宽度?【英文标题】:Howtosetcollectionviewcellwidthbasedoncontent?【发布时间】:2018-03-2413:09:34【问题描述】:我有一个水平滚动的collectionview。单元格包含一个标签。我想根据标签的内容调整单元... 查看详情

WP8 如何更改单选按钮检查的视觉状态颜色?

】WP8如何更改单选按钮检查的视觉状态颜色?【英文标题】:WP8Howtochangeradiobuttoncheckedvisualstatecolor?【发布时间】:2013-08-1909:19:09【问题描述】:我在处理WP8上的深色主题时遇到问题,未显示选中的(点)单选按钮。相同的单选... 查看详情

如何在所有设备中使用 swift4 在 CollectionView 中显示两列

】如何在所有设备中使用swift4在CollectionView中显示两列【英文标题】:HowtoshowtwocolumnsinaCollectionViewusingswift4inalldevices【发布时间】:2018-03-3011:42:57【问题描述】:为了在collectionView中只显示两列,我正在使用这段代码letlayout=self.col... 查看详情