Over and over I see claims that you can use ButtonStyle to style the appearance of NavigationLinks. But in my experience, this does not work.
What's going on here? In the screen shot, the list items (NavigationLinks) are styled with the same button style as the button below them. As you can see, this does nothing.
Code for the whole view:
// ContentView.swift
import SwiftUI
struct UserMessage : Hashable
{
var title: String
var text: String
}
let inMessages = [UserMessage(title: "Inbound 1", text: "Test message!"), UserMessage(title: "Inbound 2", text: "Test message!"), UserMessage(title: "Inbound 3", text: "Test message!")]
let outMessages = [UserMessage(title: "Outbound 1", text: "Test message!"), UserMessage(title: "Outbound 2", text: "Test message!"), UserMessage(title: "Outbound 3", text: "Test message!")]
struct NavLinkButton: ButtonStyle
{
func makeBody(configuration: Configuration) -> some View
{
configuration.label
.frame(maxWidth: .infinity)
.padding()
.foregroundStyle(.purple)
.background(configuration.isPressed ? .blue : .green)
.clipShape(RoundedRectangle(cornerRadius: 10))
.overlay {
RoundedRectangle(cornerRadius: 10)
.stroke(.red, lineWidth: configuration.isPressed ? 2 : 0)
}
.padding(3)
}
}
struct ContentView: View
{
var body: some View
{
NavigationStack
{
messageList(msgsIn: inMessages, msgsOut: outMessages)
.frame(maxWidth: 400, maxHeight: 400)
Button(action: {}, label: { Text("Styled button") })
.buttonStyle(NavLinkButton())
.frame(maxWidth: 400)
Spacer()
}
}
@ViewBuilder func messageList(msgsIn: [UserMessage], msgsOut: [UserMessage]) -> some View
{
List
{
Section(header: Text("Your Inbox"))
{
ForEach(msgsIn, id: \.self) { aMsg in
NavigationLink(destination: MessageDetailView(withMessage: aMsg), label: { Text("\(aMsg.title)") })
.buttonStyle(NavLinkButton())
}
.listRowBackground(Color.clear)
}
Section(header: Text("Your Outbox"))
{
ForEach(msgsOut, id: \.self) { aMsg in
NavigationLink(destination: MessageDetailView(withMessage: aMsg), label: { Text("\(aMsg.title)") })
.buttonStyle(NavLinkButton())
}
.listRowBackground(Color.clear)
}
}
.scrollContentBackground(.hidden)
}
}
struct MessageDetailView: View
{
var message: UserMessage?
init(withMessage: UserMessage)
{
message = withMessage
}
var body: some View
{
Text(message?.title ?? "")
}
}