如何将SwiftUI视图设置为CollectionView的单元格

swi*_*nub 7 uicollectionview uicollectionviewcell swift swiftui

我发现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),
        ])
    }
}
Run Code Online (Sandbox Code Playgroud)

第一个屏幕很好。

在此处输入图片说明

但是当我滚动到可见屏幕的尽头时,它看起来像

在此处输入图片说明

我无法自动调整单元格大小吗?还是仅仅是更多的SwiftUI错误?

[编辑] 我已经接受了SwiftUI的答案,但是如果有人可以按照此问题的要求为我提供使用UIKit的修复程序,我将接受。

iOS*_*com -2

这是一个纯粹的 SwiftUI 解决方案。它会包含您提供的任何视图,并为您提供您想要的效果。请让我知道这对你有没有用。

struct WrappedGridView: View {
    let views: [WrappedGridViewHolder]
    var showsIndicators = false
    var completion:(Int)->Void = {x in}
    var body: some View {
        GeometryReader { geometry in
            ScrollView(showsIndicators: showsIndicators) {
                self.generateContent(in: geometry)
            }
        }
    }
    
    init(views: [AnyView], showsIndicators: Bool = false, completion: @escaping (Int)->Void = {val in}) {
        self.showsIndicators = showsIndicators
        self.views = views.map { WrappedGridViewHolder(view: $0) }
        self.completion = completion
    }

    private func generateContent(in g: GeometryProxy) -> some View {
        var width = CGFloat.zero
        var height = CGFloat.zero

        return
            ZStack(alignment: .topLeading) {
                    ForEach(views) { item in
                        item
                            .padding(4)
                            .alignmentGuide(.leading) { d in
                                if (abs(width - d.width) > g.size.width) {
                                    width = 0
                                    height -= d.height
                                }
                                let result = width
                                if item == self.views.last {
                                    width = 0
                                } else {
                                    width -= d.width
                                }
                                return result
                            }
                            .alignmentGuide(.top) { d in
                                let result = height
                                if item == self.views.last {
                                    height = 0
                                }
                                return result
                            }
                            .onTapGesture {
                                tapped(value: item)
                            }
                    }
            }
            .background(
                GeometryReader { r in
                    Color
                        .clear
                        .preference(key: SizePreferenceKey.self, value: r.size)
                }
            )
    }
    
    func tapped(value: WrappedGridViewHolder) {
        guard let index = views.firstIndex(of: value) else { assert(false, "This should never happen"); return }
        completion(index)
    }
}

struct SizePreferenceKey: PreferenceKey {
    typealias Value = CGSize
    static var defaultValue: Value = .zero
    static func reduce(value: inout Value, nextValue: () -> Value) {
        
    }
}

extension WrappedGridView {
    struct WrappedGridViewHolder: View, Identifiable, Equatable {
        let id = UUID().uuidString
        let view: AnyView
        var body: some View {
            view
        }
        
        static func == (lhs: WrappedGridViewHolder, rhs: WrappedGridViewHolder) -> Bool { lhs.id == rhs.id }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这不是问题“如何将 SwiftUI 视图设置为 CollectionView 的单元格”的答案 (4认同)