Create an Image Button with Custom Color with SwiftUI

Swift for the Slow
Mac O’Clock
Published in
3 min readMay 11, 2020

If you’re a genius like me, you need many days of scouring the web and weeping in the night to learn new things like… Swift and SwiftUI.

In this little tutorial, we’ll learn to:

  1. Create a nice little “image button” that calls a function you’ve passed to it.
  2. And shows the image in 32 x 32 no matter what the size of the image was.
  3. And is dynamically colored with your own custom color.

The end result is shown below. You click the button, and whatever function you passed to the view gets called. The blue you see is a custom blue.

Here’s how you would use the code:

VImgButton(callback: { print ("hello") } , imageName: “alarm”)

Let’s get to the code, shall we? Let’s first create an Image Button.

struct VImgButton: View {// callback is the function you want to be called back when
// the button is pressed
var callback: () -> Void// An image from the system to use
var imageName: String = "folder"
var body: some View {Button(action: {self.callback()}) { VStdImg(name: imageName) // a nicely formatted image }.buttonStyle(BorderlessButtonStyle()) //don't need no stinkin' borders to this button }}

What the hell is VStdImg? Well, it's a short view that creates a standardized image that's of size 32 x 32no matter what the size of the image is. This is done by wrapping the image in a VStack of size 32 x 32, and telling the image to resize and "fill" that space.

func VStdImg(name: String, color: Color = .AppBlue) -> some View {return VStack {  Image(name)  .resizable()  .renderingMode(.template) // this one helps resize the image  .foregroundColor(color)  .aspectRatio(1, contentMode: .fit) // keep the aspect ratio }.frame(width: 32, height: 32) // the image will fit this size}

So, at this point, you have an VImgButton View ready for use. How do you use it?

Well, simple, use it wherever, like this:

VImgButton(callback: { print("oh yeah!") }, imageName: "alarm")

And that’s it! You got yourself a pretty button. Wait, what about that custom color I talked about?

Look at the signature of VStdImg - I have a default set to AppBlue - there's no system color called AppBlue, it's mine! Mine! Mine!

Here’s how you get yourself a custom color.

  1. Create a new Image set in your Xcode Assets.xcassets- give it whatever name you want (like AppBlue)
  2. Next, create an extension for Color, like this:
extension Color {static var AppOrange = Color("AppOrange")static var AppBlue = Color("AppBlue")}

And use it like this:

.foregroundColor(.AppBlue)

That’s it! Hope you found that useful.

--

--

Swift for the Slow
Mac O’Clock

Simple Swift 5+ / Swiftui 2.0 / macOS tips, utilities, sample code, some of which is used in https://powermanuscript.com