Resizing SF Symbols in SwiftUI
To create an SF Symbol in SwiftUI we use Image.init(systemName:) initializer.
When we want to resize a symbol image we shouldn't use resizable()
modifier like we do with regular images. As soon as resizable()
is used, the image stops being a symbol image. It can affect its layout and how it aligns with text.
Instead, we should use font() modifier to set the right size on the image.
We can use semantic font to set the image size that is right for its context.
Image(systemName: "paperplane")
.font(.title)
If we need to be more explicit about the size, we can also set it in points.
Image(systemName: "tray")
.font(.system(size: 20))
To scale the image relative to its font size, we should use imageScale() modifier. If we don't set the font explicitly, the symbol will get the font from the current environment.
Image(systemName: "doc")
.font(.body)
.imageScale(.small)
If you have older iOS apps and want to enhance them with modern SwiftUI features, check out my book Integrating SwiftUI into UIKit Apps. It provides detailed guidance on gradually adopting SwiftUI in your UIKit projects. Additionally, if you're eager to enhance your Swift programming skills, my latest book Swift Gems offers over a hundred advanced tips and techniques, including optimizing collections, handling strings, mastering asynchronous programming, and debugging, to take your Swift code to the next level.
I’m currently running a Black Friday 2024 promotion with 30% off my books, plus additional savings when purchased as a bundle. Visit the books page to learn more.