我是 10 年的 iOS 資深人士,但對 Swift/SwiftUI 很陌生,所以請保持溫和。我感到困惑的一件事是,如果不透明度設定為 0 或 .background(Color.clear),為什么視圖(我已經嘗試了一些,但我們使用 TextView() 為例)似乎不會被繪制。
我想要完成的是在 HStack 中放置兩個按鈕作為 ZStack 中的第一個成員(所以“回傳”最多),以確定用戶何時雙擊螢屏左側或右側,但我不希望實際顯示任何內容,只需檢測水龍頭。我的 hackish 解決方案是將不透明度設定為 0.001。使用該不透明度設定,什么都看不到,我可以用 .onTapGesture(count:2) 檢測到,但這肯定不是最佳方式。在 UIKit 領域,我很想自己使用螢屏尺寸來處理點擊坐標以確定它落在哪一側,但我認為這并不是非常“迅速”,即使它可以不包裝 UIKit 類。努力學習,所以盡可能“純 SwiftUI”。
public var body: some View {
ZStack {
HStack {
VStack {
Text("").frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color.blue)
.opacity(0.0001) //hack workaround, setting opacity to 0.0 and it's like the view isn't even drawn or present (the onTapGesture doesn't get recognized because the VStack has no size when the Text frame is zero and that's the only point! Interestingly setting the background to Color.clear creates the same issue
}.onTapGesture(count: 2) {
print("got a double tap on the LEFT side scroll button")
}
VStack {
Text("").frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color.yellow)
.opacity(0.0001)//hack workaround, setting opacity to 0.0 and it's like the view isn't even drawn or present (the onTapGesture doesn't get recognized because the VStack has no size when the Text frame is zero and that's the only point! Interestingly setting the background to Color.clear creates the same issue
}.onTapGesture(count: 2) {
print("got a double tap on the RIGHT side scroll button")
}
}
[subsequent members of the ZStack removed as they're not relevant to the question]
}
}
我想我的問題是:
a) 使用什么是不可見的,但仍用于檢測 onTapGesture?
b)如果不透明度為零或背景設定為清除,為什么 Text() 和其他視圖基本上不存在的一些知識?
謝謝!
uj5u.com熱心網友回復:
a) 使用什么是不可見的,但仍用于檢測 onTapGesture?
我們可以使用.contentShape修飾符使任何區域,甚至是完全透明的,可點擊的(又名可命中測驗的),例如:
Color.clear
.frame(width: 100, height: 100)
.contentShape(Rectangle())
.onTapGesture {
print(">>> Tapped!")
}
b)如果不透明度為零或背景設定為清除,為什么 Text() 和其他視圖基本上不存在的一些知識?
SwiftUI 將視圖呈現到一個背景關系中(它與 UIKit 中的每個 UIView 視圖都呈現自身相反),因此當視圖完全透明時,沒有任何東西可以呈現。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/442331.html
下一篇:如何填充特定的矢量/svg影像?
