In iOS, the size of buttons is typically proportional to the text or icon they contain. However, in some cases, we need buttons of uniform size. How can we achieve this? In this post, we’ll learn how to:
- Create button with the same size
- Create custom buttons
Buttons with the same size
The first thing we can try is this:
Button("Button") { // your action } .frame(maxWidth: 300, maxHeight: 60) .background(.purple) .cornerRadius(10) .overlay { RoundedRectangle(cornerRadius: 10) .stroke(.red, lineWidth: 2) }
Therefore, create buttons with the same maxWidth and maxHeight to achieve something like this:
It can look good (apart from the colors), but there is a problem. If you click on the ‘Button’ label, you see the tapped effect and the action is executed. However, if you tap outside of the text, nothing happens. This is not ideal.
Let’s take a look at a possible solution:
Button(action: {}) { Text("Button") .frame(maxWidth: 300, maxHeight: 60) .background(.purple) .cornerRadius(10) .overlay { RoundedRectangle(cornerRadius: 10) .stroke(.red, lineWidth: 2) } }
So, we now assign the action as a parameter of the Button, and the component is created within the button’s body.
Create custom buttons
Using the code we discussed earlier, we can create buttons in a multitude of ways; the only limit is our imagination (more or less):
Button(action: {}) { Text("Button") .frame(maxWidth: 200) .fontWeight(.bold) .font(.title) .padding() .background(LinearGradient(gradient: Gradient(colors: [Color.red, Color.blue]), startPoint: .leading, endPoint: .trailing)) .cornerRadius(40) .foregroundStyle(.white) .padding(10) .overlay( RoundedRectangle(cornerRadius: 40) .stroke(Color.red, lineWidth: 5) ) }
In this case, we set a width, choose the font, select the text color, apply a gradient background, and add a border with a gap.
Now, feel free to create your custom buttons, but remember not to ruin the user experience with strange designs.