[英]List in SwiftUI won't show up
I'm currently writing code for a scrollable sideways calendar that displays dates horizontally.我目前正在为水平显示日期的可滚动横向日历编写代码。 I currently have the following code (this is a very simplified version):
我目前有以下代码(这是一个非常简化的版本):
struct ScrollableCalendar: View {
var body: some View {
var someArray = [["May", "10", "2020"],["May", "11", "2020"],["May", "12", "2020"]]
ScrollView(.horizontal, showsIndicators: false) {
CalendarDateHorizBase(dates: someArray)
}
}
}
struct CalendarDateHorizBase: View {
var dates: Array<Array<String>>
var body: some View {
HStack {
****THE LOGIC ERRROR OCCURS IN THIS LIST****
List(dates, id: \.description) { date in
CalendarDate(month: date[0], day: date[1], year: date[2])
}
}
}
}
*** CalendarDate() is another view that takes a month, day, and year (all strings) and displays them nicely. *** CalendarDate() 是另一个视图,它需要一个月、一天和一年(所有字符串)并很好地显示它们。 The error is not related to CalendarDate()***
该错误与 CalendarDate() 无关***
When I attempt to hardcode the elements without the List, everything displays fine.当我尝试在没有列表的情况下对元素进行硬编码时,一切正常。 However, when I use the List, the screen becomes completely blank.
但是,当我使用列表时,屏幕变得完全空白。 I have no idea why.
我不知道为什么。 Does anyone have any ideas?
有没有人有任何想法? Thanks!
谢谢!
Your dates need to be a proper model as its not identifiable by List.您的日期需要是正确的 model,因为它无法被列表识别。
And also I believe you have some solid reason for using HStack, as I hope you know that list only goes vertically.而且我相信你有充分的理由使用 HStack,因为我希望你知道这个列表只是垂直的。
The issue is with the data.问题在于数据。 When you need to show a list of data in a
List
, each element of the data should be Identifiable
.当您需要在
List
中显示数据列表时,数据的每个元素都应该是可Identifiable
的。 One way to achieve that is to define a structure for you data and make it identifiable
:实现这一目标的一种方法是为您的数据定义一个结构并使其可
identifiable
:
struct DateEvent: Identifiable {
let id: String
let month: String
let day: String
let year: String
init(rawValue: [String]) {
month = rawValue[0]
day = rawValue[1]
year = rawValue[2]
id = rawValue.joined(separator: "/")
}
}
So now you can use it to build up your List
所以现在你可以用它来建立你的
List
struct CalendarDateHorizBase: View {
var dates: [[String]] // same as 'Array<Array<String>>' but more swifty style
var body: some View {
HStack {
List(dates.map { DateEvent(rawValue: $0) }) { date in
CalendarDate(month: date.month, day: date.day, year: date.year)
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.