Search code examples
swiftuiswiftui-navigationlink

SwiftUI NavigationLink with Button


I have the following code, and the view changes clicking anywhere in the circular button. However, the self.user.day += 1 action only executes if I click directly on the button text. This is very curious behavior to me, being new to Swift & SwiftUI in particular.

NavigationLink(destination: NewsView(), tag: 1, selection: $selection){
    Button(action: {self.selection = 1; self.user.day += 1}){
        Text("News").font(.body)
    }
    .frame(width: 100.0, height: 100.0)
    .foregroundColor(Color(red: 0.96, green: 0.96, blue: 0.47))
    .background(Color.black)
    .cornerRadius(90)
}

Any thoughts? Thanks!


Solution

  • SwiftUI will not detect taps in blank areas, no matter how big your button is, this excludes the NavigationLink.

    A simple way, in your case is just to set the frame to the text instead of the button like so

    Button(action: { print("tapped"); self.selection = 1 }) {
        Text("News").font(.body)
            .frame(width: 100.0, height: 100.0)
    }
        //.frame(width: 100.0, height: 100.0)
        .foregroundColor(Color(red: 0.96, green: 0.96, blue: 0.47))
        .background(Color.black)
        .cornerRadius(90)