How to select an item in ScrollView with SwiftUI?

[亡魂溺海] 提交于 2021-01-28 18:34:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!