Search code examples
iosswiftxcodeswiftuiipados

How Can I Change The Text By Touching Anywhere Of The Screen In SwiftUI


Hello everyone I want to change the text randomly by touching anywhere but I can just change it by touching the text.

var myArray = ["1", "2", "3"]

@State private var selectedSuggestion = Int.random(in: 0...2)

var body: some View {
    
    Text(myArray[selectedSuggestion])
        .frame(width: UIScreen.main.bounds.width * 1, height: UIScreen.main.bounds.height * 1)
        .font(.largeTitle)
        .multilineTextAlignment(.center)
        .onTapGesture {
            self.selectedSuggestion = Int.random(in: 0...2)
            
    }
}

Solution

  • The solution is to add content shape

    Text(myArray[selectedSuggestion])
        .frame(width: UIScreen.main.bounds.width * 1, height: UIScreen.main.bounds.height * 1)
        .font(.largeTitle)
        .multilineTextAlignment(.center)
        .contentShape(Rectangle())              // << here !!
        .onTapGesture {
            self.selectedSuggestion = Int.random(in: 0...2)
    
    }