如何在具有布局布局的新集合视图中将CAGradientLayer添加到UIBackgroundConfiguration?

问题描述

我想在具有布局布局的新集合视图的上下文中向集合视图单元格的背景添加渐变。这是一个示例的示例,该示例如何通过EmojiExplorerViewController的第180行中的Apple示例代码Implementing Modern Collection Views来配置单元格的背景:

func configuredGridCell() -> UICollectionView.CellRegistration<UICollectionViewCell,Emoji> {
    return UICollectionView.CellRegistration<UICollectionViewCell,Emoji> { (cell,indexPath,emoji) in
        var content = UIListContentConfiguration.cell()
        content.text = emoji.text
        content.textProperties.font = .boldSystemFont(ofSize: 38)
        content.textProperties.alignment = .center
        content.directionalLayoutMargins = .zero
        cell.contentConfiguration = content
        var background = UIBackgroundConfiguration.listPlainCell()
        background.cornerRadius = 8
        background.strokeColor = .systemGray3
        background.strokeWidth = 1.0 / cell.traitCollection.displayScale
        cell.backgroundConfiguration = background
    }
}

由于新的UIBackgroundConfiguration是结构而不是层支持UIView子类,所以我不能仅仅将CAGradientLayer实例添加为子层。

将渐变添加到单元格背景配置的一种好方法是什么?

解决方法

由于新的UIBackgroundConfiguration是结构而不是支持层的UIView子类,所以我不能仅将CAGradientLayer实例添加为子层。

是的,可以。 UIBackgroundConfiguration是一个结构这一事实是无关紧要的。它具有一个customView属性,它是一个视图,将用作单元格中的背景视图(在内容视图之后)。因此,将该视图设置为某种视图(默认情况下为nil),就一切就绪。

这是一个例子。这是用于测试目的的玩具表视图,但是测试完全是关于配置对象的,因此很容易适应于演示该技术。只要使用的是具有UIBackgroundConfiguration属性的对象,无论使用的是表格视图,集合视图还是两者都不重要。如您所见,我已经从黑色到红色做了一个垂直渐变,作为细胞的背景。

enter image description here

这是相关的代码。首先,我定义了一个梯度载体视图类型:

class MyGradientView : UIView {
    override static var layerClass: AnyClass { CAGradientLayer.self }
}

然后,在配置单元格时,我将该视图用作背景视图:

var back = UIBackgroundConfiguration.listPlainCell()
let v = MyGradientView()
(v.layer as! CAGradientLayer).colors = 
    [UIColor.black.cgColor,UIColor.red.cgColor]
back.customView = v
cell.backgroundConfiguration = back

您想要实现的任何其他功能只是上述内容的一种。例如,您可以使用图像视图或纯色背景视图,并将它们与渐变视图结合使用。关键是,customView 背景视图,并且将其设置为任何视图都将显示在单元格的背景中。

我还应该指出,还有另一种方法可以执行此操作,即使用单元格子类并实现updateConfigurationUsingState:。这种方法的优势在于,一旦您为后台配置指定了customView,您就可以在每次调用该方法时修改customView。例如,正如我在此处的其他答案(例如https://stackoverflow.com/a/63064099/341994)中所证明的那样,您可以使用此技术来响应选择。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...