我找到了 SwiftUI Text
View 非常容易使用自定义设计创建标签。所以我想将它用作常规 UIKit UICollectionViewCell 的 View 。
到目前为止,这是我的代码(您可以在 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 的修复程序,我会接受。
最佳答案
我做了一些修改并且它有效,但我认为这不是最佳实践。
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, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.frame.width/2.5, height: collectionView.frame.width/2)
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! GenericCell
cell.customView?.rootView = Text(data[indexPath.item])
return cell
}
}
func makeUIView(context: Context) -> UICollectionView {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical
let cvs = UICollectionView(frame: .zero, collectionViewLayout: layout)
cvs.dataSource = context.coordinator
cvs.delegate = context.coordinator
cvs.register(GenericCell.self, forCellWithReuseIdentifier: "cell")
cvs.backgroundColor = .white
return cvs
}
func updateUIView(_ uiView: UICollectionView, context: Context) {
}
}
public class GenericCell: UICollectionViewCell {
public var textView = Text("")
public var customView: UIHostingController<Text>?
public override init(frame: CGRect) {
super.init(frame: .zero)
customView = UIHostingController(rootView: textView)
customView!.view.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(customView!.view)
customView!.view.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
customView!.view.leftAnchor.constraint(equalTo: contentView.leftAnchor).isActive = true
customView!.view.rightAnchor.constraint(equalTo: contentView.rightAnchor).isActive = true
customView!.view.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
关于swift - 如何将 SwiftUI View 设置为 CollectionView 的单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57394518/