Swift: ColorPickers Empty Label horizontal alignment bug

  Kiến thức lập trình

The source of my problem I ran into (and only diagnosed due to the XCode “Debug View Hierarchy” tool) was being required to put an empty "" string for the native SwiftUI ColorPicker.

The problem itself is that this empty label actually takes up space in my view, thus stopping me from simply aligning my ColorPickers as such:

    private var customColorPickers: some View {
        HStack(spacing: 10) {
            Spacer()
            ForEach(0..<(colorPalettes.last?.count ?? 0), id: .self) { customIndex in
                customColorPicker(index: customIndex)
            }
            Spacer()
        }
        .frame(alignment: .center)
    }

You can see the empty view space below from the view hierarchy debugging tool (circled in red):

The solution I found was—full credit to this GitHub Gist user—from this code snippet he posted (my implementation using his struct below):

import SwiftUI

@available(iOS 14.0, *)
public struct ColorPickerWithoutLabel: UIViewRepresentable {
    @Binding var selection: Color
    var supportsAlpha: Bool = true
    
    public init(selection: Binding<Color>, supportsAlpha: Bool = true) {
        self._selection = selection
        self.supportsAlpha = supportsAlpha
    }
    
    
    public func makeUIView(context: Context) -> UIColorWell {
        let well = UIColorWell()
        well.supportsAlpha = supportsAlpha
        return well
    }
    
    public func updateUIView(_ uiView: UIColorWell, context: Context) {
        uiView.selectedColor = UIColor(selection)
    }
}

My Code Before:

ColorPicker("",
        selection: Binding(
            get: {
                // irrelevant logic for Stackoverflow answer
            },
            set: { // irrelevant logic for Stackoverflow answer
            }
        ),
        supportsOpacity: true
    )
    // irrelevant modifiers for Stackoverflow answer

My Code After (implementing this ColorPickerWithoutLabel):

ColorPickerWithoutLabel(
        selection: Binding(
            get: {
                // irrelevant logic for Stackoverflow answer
            },
            set: { // irrelevant logic for Stackoverflow answer
            }
        ),
        supportsAlpha: true
    )
    // irrelevant modifiers for Stackoverflow answer

As you can tell, the only changes were to use ColorPickerWithoutLabel, instead of ColorPicker, of course + changing supportsOpacity to supportsAlpha + removing the empty label argument ("").

After this change, you can see in the View Hierarchy Debug tool that this view space is no longer being taken up by an empty label.

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT