获取 ScrollView 元素编号 SwiftUI
Fetch ScrollView Element Number SwiftUI
我想根据单元格的编号更改ArticleListElementView
。例如我在 ScrollView
中有 10 个单元格,如果单元格编号为奇数,如 1 3 5 7 9,则显示 Rectangle()
如果单元格编号为偶数,如 0 2 4 6 8,则隐藏 Rectangle()
.所以我想我可以在 ForEach()
中将我的 cellNumber
var 增加 1,但它给了我一个错误。那我该怎么做呢?
struct ArticleView: View {
@ObservedObject var service = ArticleService()
var cellNumber: Int = 0
var body: some View {
ScrollView(.vertical, showsIndicators: false) {
LazyVGrid(columns: columns, spacing:0) {
ForEach(service.articlePost, id: \.article_id) { post in
ArticleListElementView(articlePost: post)
.onTapGesture {
self.shown = true
self.selectedArticle = post
}
cellNumberRead()
}
}
}
}
func cellNumberRead() {
cellNumber = cellNumber + 1
}
struct ArticleListElementView: View {
var articlePost: ArticlePost
var body: some View {
ZStack{
Color("Background")
.edgesIgnoringSafeArea(.all)
HStack {
// if articlePost.cellNumber == I want to check cellNumber in here and draw a line else do not draw rectangle
Rectangle()
.frame(width: 0.5, height: width)
}
这里是错误
您可以枚举数据并将索引直接插入行视图,例如
ForEach(Array(service.articlePost.enumerated()), id: \.1.article_id) { i, post in
ArticleListElementView(articlePost: post, cellNumber: i) // << here !!
现在根据需要在 ArticleListElementView 内部使用
struct ArticleListElementView: View {
var articlePost: ArticlePost
var cellNumber: Int
var body: some View {
ZStack{
Color("Background")
.edgesIgnoringSafeArea(.all)
HStack {
if cellNumber % 2 == 0 {
// .. your code
} else {
// .. another case
}
我想根据单元格的编号更改ArticleListElementView
。例如我在 ScrollView
中有 10 个单元格,如果单元格编号为奇数,如 1 3 5 7 9,则显示 Rectangle()
如果单元格编号为偶数,如 0 2 4 6 8,则隐藏 Rectangle()
.所以我想我可以在 ForEach()
中将我的 cellNumber
var 增加 1,但它给了我一个错误。那我该怎么做呢?
struct ArticleView: View {
@ObservedObject var service = ArticleService()
var cellNumber: Int = 0
var body: some View {
ScrollView(.vertical, showsIndicators: false) {
LazyVGrid(columns: columns, spacing:0) {
ForEach(service.articlePost, id: \.article_id) { post in
ArticleListElementView(articlePost: post)
.onTapGesture {
self.shown = true
self.selectedArticle = post
}
cellNumberRead()
}
}
}
}
func cellNumberRead() {
cellNumber = cellNumber + 1
}
struct ArticleListElementView: View {
var articlePost: ArticlePost
var body: some View {
ZStack{
Color("Background")
.edgesIgnoringSafeArea(.all)
HStack {
// if articlePost.cellNumber == I want to check cellNumber in here and draw a line else do not draw rectangle
Rectangle()
.frame(width: 0.5, height: width)
}
这里是错误
您可以枚举数据并将索引直接插入行视图,例如
ForEach(Array(service.articlePost.enumerated()), id: \.1.article_id) { i, post in
ArticleListElementView(articlePost: post, cellNumber: i) // << here !!
现在根据需要在 ArticleListElementView 内部使用
struct ArticleListElementView: View {
var articlePost: ArticlePost
var cellNumber: Int
var body: some View {
ZStack{
Color("Background")
.edgesIgnoringSafeArea(.all)
HStack {
if cellNumber % 2 == 0 {
// .. your code
} else {
// .. another case
}