问题
what I am trying to accomplish is have a loop of items where I am able to tap one and it gets bigger programmatically once tapped
here is my code and my results so far:
struct ContentView: View {
@State var emojisArray = ["📚", "🎹", "🎯", "💻"]
@State var selectedIndex = 0
var body: some View {
VStack {
ScrollView(.horizontal) {
HStack {
ForEach(0..<emojisArray.count) { item in
emojiView(emoji: self.emojisArray[item],
isSelected: item == self.selectedIndex ? true : false)
.onTapGesture {
print (item)
self.selectedIndex = item
}
}
}
}
.onAppear()
.frame(height:160)
VStack{
Text("selcted item:")
Text("\(self.emojisArray[self.selectedIndex])")
}
}
}
}
where emojiView is :
struct emojiView: View {
var emoji : String
@State var isSelected : Bool
var body: some View {
Text(emoji)
.font(isSelected ? .system(size: 120) : .system(size: 45))
}
}
I guess the problem is that the ScrollView does't reload itself
回答1:
Just remove @State
in emojiView
struct emojiView: View {
var emoji : String
var isSelected : Bool // << here !!
var body: some View {
Text(emoji)
.font(isSelected ? .system(size: 120) : .system(size: 45))
}
}
Tested with Xcode 12 / iOS 14
来源:https://stackoverflow.com/questions/63297201/how-to-select-an-item-in-scrollview-with-swiftui