[英]How to use a generic array - SwiftUI
Hi I'm creating a component that needs to consider an array for its operation.您好我正在创建一个组件,该组件需要考虑其操作的数组。
I created a model for displaying the array like this我创建了一个 model 来显示这样的数组
struct FeaturedWorksModel: Identifiable {
var id = UUID()
var image: String
var title: String
}
var featuredWorksItems: [FeaturedWorksModel] = [
FeaturedWorksModel(image: "slider1", title: "TAGLIO CREATIVO"),
FeaturedWorksModel(image: "slider4", title: "LOREM IPSUM"),
FeaturedWorksModel(image: "slider3", title: "NEQUE EST DOLOR"),
FeaturedWorksModel(image: "slider2", title: "CONSECTETUR, INTEGER ERAT AUGUE ")
]
Now my component can also be used with other arrays and I wanted to know how I can define a generic array within the component initialization parameters in order to reuse the component even referring to arrays other than the one I am using in this moment现在我的组件也可以与其他 arrays 一起使用,我想知道如何在组件初始化参数中定义一个通用数组,以便重用该组件,甚至引用 arrays 而不是我现在使用的那个
This is the component I am using to which I will have to pass the reference array for it to work这是我正在使用的组件,我必须将参考数组传递给它才能工作
struct SmoothPager: View {
@Binding var offset: CGPoint
var body: some View {
HStack(spacing: 10) {
ForEach(featuredWorksItems.indices) { works in
Capsule()
.fill(getIndex() == works ? .white : .gray)
.frame(width: getIndex() == works ? 15 : 7, height: 7)
}
}
.overlay(
Capsule()
.fill(.white)
.frame(width: 15, height: 7)
.offset(x: getOffset())
, alignment: .leading
)
}
func getIndex()-> Int {
let index = Int(round(Double(offset.x / screen.width)))
return index
}
func getOffset()-> CGFloat {
let progress = offset.x / screen.width
return 17 * progress
}
}
In this case I am using featuredWorksItems.indices
but I wanted to make the component reusable with other similar arrays as well.在这种情况下,我使用
featuredWorksItems.indices
但我想让组件也可与其他类似的 arrays 一起使用。 What is the best way to pass a generic array parameter in this structure?在此结构中传递通用数组参数的最佳方法是什么?
Do you mean something like你的意思是像
struct SmoothPager<Element: Identifiable>: View {
@Binding private var offset: CGPoint
private let elements: [Element]
init(elements: [Element], offset: Binding<CGPoint>) {
self.elements = elements
self._offset = offset
}
var body: some View {
HStack(spacing: 10) {
ForEach(elements.indices) { works in
Capsule()
.fill(getIndex() == works ? .white : .gray)
.frame(width: getIndex() == works ? 15 : 7, height: 7)
}
}
.overlay(
Capsule()
.fill(.white)
.frame(width: 15, height: 7)
.offset(x: getOffset())
, alignment: .leading
)
}
func getIndex()-> Int {
let index = Int(round(Double(offset.x / UIScreen.main.bounds.width)))
return index
}
func getOffset()-> CGFloat {
let progress = offset.x / UIScreen.main.bounds.width
return 17 * progress
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.