5

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

enter image description here

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

oh yeah it works but only in the simulator not in the preview, I should have imagine,
this is not really selecting the element. This is a visual hack to give the impression the element is selected.
@Duck "selected" doesn't have a universal meaning; it means whatever the designer of the app decides it means. Making the element look selected is a perfectly normal, non-hack aspect of what it means to be selected

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.