如何通过在 SwiftUI 中触摸屏幕的任何位置来更改文本



大家好,我想通过触摸任何地方来随机更改文本,但我可以通过触摸文本来更改它。

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)

}
}

解决方案是添加内容形状

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)
}

相关内容

最新更新