代码:我只想在选定的按钮视图上打勾,并需要选定的按钮 schoolCode 但我的代码我也得到了复选标记,并且也选定了按钮代码,但如果我选择按钮,其位置会发生变化..如果我选择第三个按钮,那么它就这样来到了第二位...请修复这个错误
ScrollView(.horizontal, showsIndicators: false) {
HStack {
if let retrievedArray = UserDefaults.standard.stringArray(forKey: "SavedSchoolCodes") {
let uniqueItems = Array(Set(retrievedArray))
ForEach(uniqueItems, id: \.self) { item in
if let school = schoolList.first(where: { $0.schoolCode == item }) {
Button {
viewModel.schoolCode = school.schoolCode ?? ""
} label: {
ZStack {
let correctedPhotoURL = school.logo?.replacingOccurrences(of: "//SchImg", with: "/SchImg") ?? ""
VStack {
URLImageView(url: correctedPhotoURL, placeholder: "NoProfilePic", width: 50, height: 50)
.clipShape(Circle())
.padding(.bottom, 4)
Text(school.schoolCode ?? "")
.font(.headline)
.foregroundColor(.black)
}
.frame(width: 100, height: 120)
.background(Color.gray.opacity(0.2))
.cornerRadius(10)
RoundedRectangle(cornerRadius: 10)
.stroke(viewModel.schoolCode == school.schoolCode ? Color.green : Color.clear, lineWidth: 2)
.frame(width: 100, height: 120)
if viewModel.schoolCode == school.schoolCode {
Image(systemName: "checkmark.circle.fill")
.resizable()
.frame(width: 20, height: 20)
.foregroundColor(.green)
.offset(x: 35, y: -45)
}
}
}
.padding(5)
} else {
Text("\(item),")
}
}
} else {
Text("No array found in UserDefaults.")
}
}
.padding(.horizontal)
}
o/p:当我选择时,我只想勾选标记,就是这样..请指导修复更改位置。
您将学校代码列表转换为
Set
,然后迭代该集合并找到每个代码对应的 School
。
A
Set
是一个无序集合。因此,您视图中学校的顺序是不可预测的,并且当重新渲染视图以显示所选学校时,它似乎确实发生了变化。
尝试对您从
Set
创建的数组进行排序:
let uniqueItems = Array(Set(retrievedArray)).sorted()