Search code examples
swiftuicollectionviewuikituicollectionviewlistcell

How to set accessibilityIdentifier to UICollectionViewListCell accessory?


I need to expand/collapse my cell in my tests automation which relies on accessibilityIdentifier field in UIViews.

This is how I set my accessory to the cell:

func headerCellRegistartion(
) -> UICollectionView.CellRegistration<MyCollectionViewListCell, MyStruct> {
    UICollectionView.CellRegistration<MyCollectionViewListCell, MyStruct>(
        cellNib: MyCollectionViewListCell.nib(MyCollectionViewListCell.self)
    ) { cell, indexPath, headerItem in
        let headerDisclosureOption = UICellAccessory.OutlineDisclosureOptions(
            style: .header,
            tintColor: .systemGray)
            
        cell.accessories = [
            .outlineDisclosure(displayed: .whenNotEditing, options: headerDisclosureOption),
        ]
    }
}

MyCollectionViewListCell is a subclass of UICollectionViewListCell. UICellAccessory.OutlineDisclosureOptions doesn't have any options to configure such fields. What are my options in this case?


Solution

  • The solution is to subclass the UICollectionViewListCell and override the didAddSubview method like so:

    override func didAddSubview(_ subview: UIView) {
        super.didAddSubview(subview)
        
        if subview.className().hasSuffix("Disclosure") {
            subview.accessibilityIdentifier = "myIdentifier"
        }
    }