rfarias
rfarias

Reputation: 1406

How to disable SwiftUI's default behavior?

SwiftUI makes it very easy to build declarative UIs. However, sometimes they assume defaults that are not necessarily what we want.

Example:

When adding two buttons inside a list row, SwiftUI automatically makes the whole row touchable, and both button's actions are called on row tap. This is the default behavior, as demonstrated in their WWDC videos.

But I do not want this behavior. I want both buttons to work properly, and the row to not be tappable.

Question:

How can we tell our Guacamole expert (to use the WWDC reference) to stop assuming how I want my list (or any other behavior) to work?

Any help would be appreciated.

Upvotes: 1

Views: 680

Answers (2)

yawnobleix
yawnobleix

Reputation: 1342

I am under the impression that Apple wants to enforce their style guidelines. Also to add onto @backslash-f answer you could also just use a for each instead of a list, this will give you a similar effect and allow much more customization.

struct doubleList: View {
    var body: some View {
        VStack{
            ForEach(1 ..< 10) {index in
               Button(action: {
                   print("foo")
               }) {
                   Image(systemName: "photo")
                   }
               }
           }
       }
}

Another option to try would be to wrap an UITableView into an UIViewRepresentable and try to enable buttons that way

It seems there might be another way around this by using tap gestures

Image(systemName: "photo")
.gesture(TapGesture().onEnded() {
                print("action2")
                })

Upvotes: 1

backslash-f
backslash-f

Reputation: 8183

If the List's default behavior is not required, you could use a VStack:

struct ContentView: View {
    var body: some View {
        VStack {
            Button(action: {
                print("foo")
            }) {
                Image(systemName: "photo")
            }
            Button(action: {
                print("bar")
            }) {
                Image(systemName: "photo")
            }
        }
    }
}

However if List is really required, then it could be customized by writing a custom ListStyle.

(Also take a look at this question: How to change ListStyle in List.)

It seems that SomethingStyle protocol is the way Apple wants developers to use to modify native SwiftUI elements/behavior. Another example would be ButtonStyle or TextFieldStyle, etc.

Upvotes: 1

Related Questions