avatar

SwiftUI-ContentShape

What I encountered.

Recently when I’m testing Tap Gesture, but however I’ve got in some trouble. And touch event doesn’t work.

However, after find some answers on stackoverflow. I noticed that Color.clear’s contentShape is zero, which means it is untouchable.

And the solution is to add modifier .contentShape(Rectangle()) before .onTapGesture modifier.

Here’s my test code. You can comment or uncommnet the contentShape modifier to see what happened.

import SwiftUI

struct TapView: View {
@State var state = ""

var body: some View {
ZStack {
Color.yellow
.onTapGesture(count: 1, perform: {
self.state = "yellow"
})

ZStack {
Color.clear
// .contentShape(Rectangle())
.onTapGesture(count: 1, perform: {
print("www")
self.state = "clear"
})

.border(Color.black)

VStack {
Text("Title")
.onTapGesture(count: 1, perform: {
self.state = "Title"
})
Text(state)
.foregroundColor(.red)
}
.padding()
.border(/*@START_MENU_TOKEN@*/Color.black/*@END_MENU_TOKEN@*/)
// .contentShape(Rectangle())
.onTapGesture(count: /*@START_MENU_TOKEN@*/1/*@END_MENU_TOKEN@*/, perform: {
self.state = "Vstack"
})
}

}
.frame(width: 300, height: 300, alignment: .center)
}
}

struct TapView_Previews: PreviewProvider {
static var previews: some View {
TapView()
}
}

Something about ContentShape

In Hacking with Swift 100 days learning SwiftUI, it mentioned that when adding gestures to a Stack, it will allocate gestures to the Views in this Stack, but area that outside the Views, and inside the Stack is not. So, if we want to add some gestures to a Stack, we can use .contentShape() modifier.

文章作者: X Mεl0n
文章链接: http://www.zrzz.site/2020/09/07/SwiftUI-ContentShape/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 X Mεl0n | 随手记

评论