在单元格中使用 UIHostingConfiguration 时删除填充?

zum*_*zum 3 uikit ios uicollectionview swift swiftui

我试图弄清楚如何删除当我UIHostingConfigurationUICollectionView. 例如使用以下代码:

https://github.com/mvemjsun/CollectionView

如果我添加边框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
    }
}
    
Run Code Online (Sandbox Code Playgroud)

它显示了我正在谈论的填充:

在此输入图像描述

我在其他项目中也有同样的行为。我希望闭包内的 SwiftUI 视图UIHostingConfiguration填充单元格的整个空间,这样在这种情况下红色边框将与蓝色边框重叠。

我怎样才能做到这一点?

zum*_*zum 16

我找到了解决方案。

let cellRegistration = 
UICollectionView.CellRegistration<UICollectionViewCell, ToDoListItem> { cell, indexPath, item in
    cell.contentConfiguration = UIHostingConfiguration {
        CellView(toDoListItem: item)
    }
    .margins(.all, 0) // <--- this line
}
    
Run Code Online (Sandbox Code Playgroud)

  • 根据您想要执行的操作,您可能希望将 SwiftUI 视图放在“UIHostingConfiguration”上的“.background”修饰符中,并为内容留出边距。请参阅[文档](https://developer.apple.com/documentation/SwiftUI/UIHostingConfiguration)中的示例。背景在单元格中从边到边延伸,没有任何默认边距/插图。 (3认同)