我在 macOS (12.x) 上遇到了 SwiftUI 的問題,其中縮放背景干擾了滑鼠點擊。以下是一個最小示例:
struct ContentView: View {
var body: some View {
VStack {
Button("Test") {
print("Tested")
}
Image(systemName: "waveform.circle")
.resizable()
.frame(width: 200, height: 200)
.background(
Image(systemName: "waveform.circle")
.resizable()
.foregroundColor(.red)
.scaleEffect(2.0)
.blur(radius: 20)
.clipped()
)
}
.frame(width: 500, height: 500)
}
}
請注意,按下“測驗”按鈕實際上不起作用——沒有向控制臺列印任何訊息。
我找到了一種使用 的解決方法NSHostingView,但它非常難看——我很想知道是否有一個純 SwiftUI 解決方案來“剪輯”背景視圖,這樣不僅可以截斷它的外觀,還可以攔截點擊。
這是一種解決方法(請注意,關閉縮放效果也可以解決問題)。
struct ContentViewWorkAround: View {
@State private var scaleEffectOn = true
@State private var workAround = false
@ViewBuilder private var imageBackground: some View {
switch workAround {
case false:
Image(systemName: "waveform.circle")
.resizable()
.foregroundColor(.red)
.scaleEffect(scaleEffectOn ? 2.0 : 1.0)
.blur(radius: 20)
.clipped()
.frame(width: 200, height: 200) // ineffective at preventing clicks
case true:
NSHostingViewRepresented {
Image(systemName: "waveform.circle")
.resizable()
.foregroundColor(.green)
.scaleEffect(2.0)
.blur(radius: 20)
.clipped()
.frame(width: 200, height: 200)
}
}
}
var body: some View {
VStack {
Button("Test") {
print("Tested")
}
Image(systemName: "waveform.circle")
.resizable()
.frame(width: 200, height: 200)
.background(
imageBackground
)
Toggle("Scale effect", isOn: $scaleEffectOn)
Toggle("Workaround", isOn: $workAround)
}
.frame(width: 500, height: 500)
}
}
struct NSHostingViewRepresented<V>: NSViewRepresentable where V: View {
var content: () -> V
func makeNSView(context: Context) -> NSHostingView<V> {
NSHostingView(rootView: content())
}
func updateNSView(_ nsView: NSHostingView<V>, context: Context) { }
}
uj5u.com熱心網友回復:
你有沒有嘗試過?
.allowsHitTesting(false)
停用點擊并允許您想要的任何外觀。
struct ContentView: View {
var body: some View {
VStack {
Button("Test") {
print("Tested")
}
Image(systemName: "waveform.circle")
.resizable()
.frame(width: 200, height: 200)
.background(
Image(systemName: "waveform.circle")
.resizable()
.foregroundColor(.red)
.scaleEffect(2.0)
.blur(radius: 20)
.clipped()
.allowsHitTesting(false)
)
}
.frame(width: 500, height: 500)
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/517832.html
標籤:迅速苹果系统迅捷
