How to Align Items to the Leading in Picker

Picker align items center by default, but developers could change the default alignment by custom views. Assume that we need a color picker, which list three colors with a colored rectangle and the color name. Compare with the default style and the custom style as below:

Default Alignment
Custom Alignment

Well, the right one is much more beautiful than the left, and that’s what we want. Let’s do it step by step!

1. Extension the Color. We need a color array and use it with ForEach, so the Color should implements the Identifiable protocol. We override the id variable and specify its return type to be String. The id will return the color name in this tutorial as the code below.

extension Color: Identifiable {
    public var id: String {
        self.description
    }
}

Additionally, Extensions add new functionality to an existing class, structure, enumeration, or protocol type. This includes the ability to extend types for which you don’t have access to the original source code. That’s why we use extension instead of a custom color type in this tutorial.

2. Declare a color array. We store red, green, and blue in an array. Notice that each item in the color array is a Color structure, and its id equals its color name.

var colors: [Color] = [.red, .green, .blue]

3. Create a Picker with a custom alignment. We draw a rectangle and a text in an HStack, which is considered as our custom view. Then, we set the frame of Text by the frame modifier, with the alignment parameter to be leading.

struct ContentView: View {
    
    @State private var color: Color = .red
    
    var body: some View {
        Picker("Select color", selection: $color) {
            ForEach(colors) { color in
                HStack() {
                    color.aspectRatio(contentMode: .fit)
                    Text(color.id)
                        .frame(width: 100, height: 30, alignment: .leading)
                }
            }
        }
    }
}

The alignment parameter is center by default, therefore we have to specify its value manually. Notice that use this method to specify a fixed size for a view’s width, height, or both. If you only specify one of the dimensions, the resulting view assumes this view’s sizing behavior in the other dimension.

Conclusion

We have learned the way to align items in Picker. For the frame modifier, the alignment parameter specifies this view’s alignment within the frame. In additional, the alignment parameter applies if this view is smaller than the size given by the resulting frame.

Leave a Reply

Your email address will not be published. Required fields are marked *