如何在 SwiftUI 中将苹果 ColorPicker 的布局从圆形更改为方形?

How can I change layout of apple ColorPicker from Circle to Square in SwiftUI?

ColorPicker 默认的按钮样式是一个圆形,如下图。

我想把圆形按钮的样式改成矩形。但似乎没有API可以改变它的风格。所以我在上面放了一个矩形,并将它的 allowsHitTesting 设置为 false 以将点击事件传输到 ColorPicker。

struct ColorPickerView: View {
    @State private var colorValue = Color.orange
    var body: some View {
        ZStack() {
            ColorPicker("", selection: $colorValue)
                .labelsHidden()
            Rectangle()
                .foregroundColor(.blue)
                .frame(width: 40, height: 40, alignment: .center)
                .allowsHitTesting(false)
        }
    }
}

但是点击后没有出现拾色器

我在Rectangle下面画了一个圆圈来测试allowsHitTesting是否有用。它可以正常响应点击手势打印“Circle tapped!”。

struct ColorPickerView: View {
    @State private var colorValue = Color.orange
    var body: some View {
        ZStack() {
            ColorPicker("", selection: $colorValue)
                .labelsHidden()
            Rectangle()
                .foregroundColor(.blue)
                .frame(width: 40, height: 40, alignment: .center)
                .onTapGesture {
                    print("Circle tapped!")
                }
            Rectangle()
                .foregroundColor(.blue)
                .frame(width: 40, height: 40, alignment: .center)
                .allowsHitTesting(false)
        }
    }
}

为什么ColorPicker无法响应点击手势?或者有没有自定义ColorPicker按钮的方法?

只需使用 opacity,然后将 ColorPicker 发送到 overlay,如代码中所示:


struct SquareColorPickerView: View {
    
    @Binding var colorValue: Color
    
    var body: some View {
        
        colorValue
            .frame(width: 40, height: 40, alignment: .center)
            .cornerRadius(10.0)
            .overlay(RoundedRectangle(cornerRadius: 10.0).stroke(Color.white, style: StrokeStyle(lineWidth: 5)))
            .padding(10)
            .background(AngularGradient(gradient: Gradient(colors: [.red,.yellow,.green,.blue,.purple,.pink]), center:.center).cornerRadius(20.0))
            .overlay(ColorPicker("", selection: $colorValue).labelsHidden().opacity(0.015))
            .shadow(radius: 5.0)

    }
}

用例:

struct ContentView: View {
    
    @State private var colorValue = Color.orange
    
    var body: some View {

        SquareColorPickerView(colorValue: $colorValue)

    }
}