Selectable Tags in SwiftUI
Learn how to build custom selectable tags view in SwiftUI
SwiftUI is a framework for building user interfaces on Apple platforms. With its easy-to-use syntax, developers can create powerful and interactive user interfaces with less code. In this article, we will learn how to use the Layout Protocol to implement the selectable tags view in SwiftUI.
You traditionally arrange views in your app’s user interface using built-in layout containers like HStack
and Grid
. If you need more complex layout behavior, you can define a custom layout container by creating a type that conforms to the Layout
protocol and implementing its required methods:
sizeThatFits(proposal:subviews:cache:)
reports the size of the composite layout view.placeSubviews(in:proposal:subviews:cache:)
assigns positions to the container’s subviews.
sizeThatFits
calculate and return the size of the layout container, and placeSubviews
tell each subview where to appear.
Let's look at how we can use this to create a selectable tag view in SwiftUI
Tag Struct
We will start by creating a Tag struct, this will give us access to properties such as name to display it in our view, and the isSelected Boolean to select/unselect a…