如何使用选定但未聚焦的UICellAccessory.customView设置正确的tintColor

问题描述 投票:0回答:1

UICollectionView
布局内的
UISplitViewController
中,我有一个
UICollectionViewListCell
,在适用时将警告徽章显示为
UICellAccessory

此警告徽章配件基于以下代码:

func warningBadge(cell: UICollectionViewListCell) -> UICellAccessory  {

    return UICellAccessory.customView(configuration: 
    .init(customView: UIImageView(image: UIImage(systemName: "exclamationmark.triangle")), 
 reservedLayoutWidth: .custom(18), 
           tintColor: UIColor(dynamicProvider: { collection in

        if cell.isSelected {
            return .lightText
        }
        else {
            return .systemRed
        }
    })))
}

这工作正常,除非应用程序中的焦点移动到分割视图控件中的另一个部分。

在这种情况下,选定的单元格显示浅灰色背景,而不是 TintColor 背景(这是正确的),但警告徽章仍然具有选定的外观,这使得很难看到(浅灰色背景上的浅色文本)。

如果单元格被选中但未聚焦,则图像应具有未选中的tintColor(在此示例代码中为

.systemRed
)。

我尝试使用

cell.isFocused
代替或补充
cell.isSelected
,但这不起作用。

有趣的是,

cell.isFocused
确实适用于
UICellAccessory.label
配件,但显然不适用于带有图像控件的
UICellAccessory.customView

当选择单元格但未聚焦时,如何为自定义配件提供正确的色调颜色?

ios swift uicollectionview uicollectionviewcell uicollectionviewcompositionallayout
1个回答
0
投票

这里的问题是,即使单元格被选中但未聚焦,自定义附件也会保留其外观。为了解决这个问题,您可以采用以下方法:

您还可以利用

cell.isSelected
为自定义附件中的图像正确设置
cell.isFocused
,而不是仅仅依赖
tintColor
。然而,正如您所注意到的,
cell.isFocused
似乎不适用于带有图像控件的
UICellAccessory.customView

要解决此问题,您可以将自定义

UIImageView
包装在
UIView
中,然后为该
tintColor
设置
UIView
。这将使您能够根据单元格的状态正确设置
tintColor

以下是实施方法:

func warningBadge(cell: UICollectionViewListCell) -> UICellAccessory  {
    let imageView = UIImageView(image: UIImage(systemName: "exclamationmark.triangle"))
    imageView.tintColor = cell.isSelected ? .lightText : .systemRed
    
    let containerView = UIView()
    containerView.addSubview(imageView)
    
    // Set desired constraints for imageView here if necessary
    // For example:
    // imageView.translatesAutoresizingMaskIntoConstraints = false
    // imageView.centerXAnchor.constraint(equalTo: containerView.centerXAnchor).isActive = true
    // imageView.centerYAnchor.constraint(equalTo: containerView.centerYAnchor).isActive = true
    
    return UICellAccessory.customView(configuration: .init(customView: containerView, reservedLayoutWidth: .custom(18)))
}

这应该允许您根据单元格的状态在自定义附件中正确设置图像的

tintColor
,无论它是否聚焦。

© www.soinside.com 2019 - 2024. All rights reserved.