SwiftUI overlay blocking List scroll events

青春壹個敷衍的年華 提交于 2021-01-27 13:18:49

问题


I'd like to put a semi-transparent image overlay on top of the list in SwiftUI. I've tried the code like this:

struct ContentView: View {
    var body: some View {
        List {
            Text("first")
            Text("second")
            Text("third")
        }
        .overlay(
            Image(systemName: "hifispeaker")
                .resizable()
                .frame(width: 200, height: 200)
                .opacity(0.15)
        )
    }
}

It looks as expected, but if you place your finger within image boundaries the scrolling of the list doesn't work (if you try to scroll outside the image it works fine)

I've tried to add .allowsHitTesting(false) right after opacity, but it doesn't change anything.

Using ZStack instead of overlay doesn't help too. The only workaround I've found is to use ZStack, place the image behind the list and make the list semi-transparent, but it's not the solution I'm looking for (it changes the colors of the list slightly and causes some issues with animations).

Is there a way to make it work? Like making the image pass events to the list in the background or something.


回答1:


This definitely seems like a SwiftUI bug. I encountered the same issue and was able to find a workaround.

struct ContentView: View {
    var body: some View {
        List {
            Text("first")
            Text("second")
            Text("third")
        }
        .overlay(
            ScrollView {
                Image(systemName: "hifispeaker")
                    .resizable()
                    .frame(width: 200, height: 200)
                    .opacity(0.15)
            }
            .frame(width: 200, height: 200)
            .disabled(true)
        )
    }
}

By embedding your overlay in a ScrollView with the .disabled(true) modifier, the gestures pass through to the list properly and scrolling is not blocked.



来源:https://stackoverflow.com/questions/62061093/swiftui-overlay-blocking-list-scroll-events

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!