1

I am trying to figure out how to remove the padding I get when I use UIHostingConfiguration to use a SwiftUI view in a UICollectionView. For example using this code:

https://github.com/mvemjsun/CollectionView

If I add a border to the CellView:

/// Create a cell registration of type UICollectionViewCell with `ToDoListItem` that will be used to provide the collection view cells.
/// This will
let cellRegistration = UICollectionView.CellRegistration<UICollectionViewCell, ToDoListItem> { cell, indexPath, item in
        cell.contentConfiguration = UIHostingConfiguration {
            CellView(toDoListItem: item)
                .border(.red)// <-- I want this border to match the blue border...
        }
        cell.layer.borderWidth = 1
        cell.layer.borderColor = UIColor.blue.cgColor //<-- this shows the actual cell size I want my swiftui view to fill
    }
}
    

It shows the padding I am talking about:

enter image description here

I have the same behavior in other projects. I want the SwiftUI view inside UIHostingConfiguration closure to fill the entire space of the cell so that in this case that red border would overlap the blue border.

How can I do that?

zumzum
  • 17,984
  • 26
  • 111
  • 172

1 Answers1

12

I found the solution.

let cellRegistration = 
UICollectionView.CellRegistration<UICollectionViewCell, ToDoListItem> { cell, indexPath, item in
    cell.contentConfiguration = UIHostingConfiguration {
        CellView(toDoListItem: item)
    }
    .margins(.all, 0) // <--- this line
}
    
zumzum
  • 17,984
  • 26
  • 111
  • 172
  • 1
    Depending on what you are trying to do, you may instead want to put SwiftUI views in the `.background` modifier on `UIHostingConfiguration`, and leave the margins for the content. See the examples in the [documentation](https://developer.apple.com/documentation/SwiftUI/UIHostingConfiguration). The background extends edge-to-edge in the cell, without any default margins/insets. – smileyborg Nov 07 '22 at 23:08