Search code examples
swiftuiswiftui-button

Display curved button with custom color


I am trying to achieve a Scrollview with buttons that have rounded corners and a custom color.

Button(shoppingListItem.text) {
  removeFromShoppingList(itemId: shoppingListItem.item_id)
}
.overlay(
  RoundedRectangle(cornerRadius: 20)
    .stroke(Color.secondary, lineWidth: 2)
    .background(
      RoundedRectangle(cornerRadius: 20, style: .continuous)
        .fill(Color("ShoppingListItemColor"))
    )
  )
)

This results in a button with rounded corners and the wanted color but no text is visible. What am I missing here?


Solution

  • You might be better writing your code this way...

    Button(shoppingListItem.text) {
      removeFromShoppingList(itemId: shoppingListItem.item_id)
    }
    .overlay(
      RoundedRectangle(cornerRadius: 20)
        .stroke(Color.secondary, lineWidth: 2)
    )
    .background(Color("ShoppingListItemColor"))
    .clipShape(RoundedRectangle(cornerRadius: 20))
    

    In this I have moved the background out of the overlay.

    • So this is now built from a button with text.
    • The button has an overlay of just the border of a rounded rectangle.
    • Then the button has a background color.
    • And then the button is clipped by a rounded rectangle.

    In your code (probably because of the lack of formatting) you had inadvertently added the background to the overlay. So you had overlaid the whole button with the background colour and covered the text.