我发现Text
使用自定义设计创建Label的SwiftUI 视图非常容易。因此,我想将其用作常规UIKit UICollectionViewCell的视图。
到目前为止,这是我的代码(您可以在Xcode 11中复制和粘贴)。
import SwiftUI import UIKit struct ContentView: View { var body: some View { CollectionComponent() } } #if DEBUG struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } #endif struct CollectionComponent : UIViewRepresentable { func makeCoordinator() -> CollectionComponent.Coordinator { Coordinator(data: []) } class Coordinator: NSObject, UICollectionViewDataSource, UICollectionViewDelegate { var data: [String] = [] init(data: [String]) { for index in (0...1000) { self.data.append("\(index)") } } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { data.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! GenericCell cell.customView.rootView = AnyView( Text(data[indexPath.item]).font(Font.title).border(Color.red) ) return cell } } func makeUIView(context: Context) -> UICollectionView { let layout = UICollectionViewFlowLayout() layout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize layout.scrollDirection = .vertical let cv = UICollectionView(frame: .zero, collectionViewLayout: layout) cv.dataSource = context.coordinator cv.delegate = context.coordinator cv.register(GenericCell.self, forCellWithReuseIdentifier: "cell") cv.backgroundColor = .white layout.minimumInteritemSpacing = 0 layout.minimumLineSpacing = 0 return cv } func updateUIView(_ uiView: UICollectionView, context: Context) { } } open class GenericCell: UICollectionViewCell { public var customView = UIHostingController(rootView: AnyView(Text(""))) public override init(frame: CGRect) { super.init(frame: frame) configure() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configure() } private func configure() { contentView.addSubview(customView.view) customView.view.preservesSuperviewLayoutMargins = false customView.view.translatesAutoresizingMaskIntoCOnstraints= false NSLayoutConstraint.activate([ customView.view.leftAnchor.constraint(equalTo: contentView.layoutMarginsGuide.leftAnchor), customView.view.rightAnchor.constraint(equalTo: contentView.layoutMarginsGuide.rightAnchor), customView.view.topAnchor.constraint(equalTo: contentView.layoutMarginsGuide.topAnchor), customView.view.bottomAnchor.constraint(equalTo: contentView.layoutMarginsGuide.bottomAnchor), ]) } }
第一个屏幕很好。
但是当我滚动到可见屏幕的尽头时,它看起来像
我无法自动调整单元格大小吗?还是仅仅是更多的SwiftUI错误?
[编辑] 我已经接受了SwiftUI的答案,但是如果有人可以按照此问题的要求为我提供使用UIKit的修复程序,我将接受。