简体   繁体   中英

Swift UI List: Open external URL when cell is tapped

I am trying to open a URL when one of the List 's cells is tapped. I tried adding the modifier onTapGesture to the cell itself and then calling UIApplication.shared.open(url) , but this only works if the tap is right on the cell view's elements (and not on the cell's background).

I also tried to add a background view (Rectangle) to the cell with opacity 0.01, but although this works the Rectangle is quite visible despite its low opacity.

Is there any workaround to make the whole row tappable?

Found a solution, here it is in case it helps anyone in the future:

// edit:

Used a single Button , with the required action (ie openURL in my case) in the action closure, and with my custom view returned in the label closure.

@stakri, What you're looking for is ".contentShape()"

Rectangle()
    .stroke()
    .onTapGesture() {
        UIApplication.shared.open(URL(string: "https://stackoverflow.com")!)
    }

above code will only work if you tap on the 'stroke' outline of the rectangle, but.contentShape() will make the entire area tappable without the need to nest it inside of a Stack:

Rectangle()
    .stroke()
    .contentShape( Rectangle() )
    .onTapGesture() {
        UIApplication.shared.open(URL(string: "https://stackoverflow.com")!)
    }

Others coming to this question will likely be looking for how to specifically open a URL, you'll notice I force unwrapped my URL. Open to feedback on that, but barring any issues brought up, this works well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM