SwiftUI选择器SegmentedStyle图像显示错误

时间:2020-01-07 20:18:53

标签: swift image swiftui uisegmentedcontrol picker

我在SegmentedStyle中有一个简单的选择器,里面有两个图像:

@State var selectedIndex = 0

    @State var segmentOptions = [
        Image.carFill,
        Image.walking
    ]
    //@State var destination: Destination

    var body: some View {
        HStack {
            Picker(selection: $selectedIndex, label: Text("")) {
                segmentOptions[0]
                    .tag(0)
                segmentOptions[1]
                    .tag(1)
            }.pickerStyle(SegmentedPickerStyle())
            Text("test")
        }
    }

首先是来自SF Symbol的图像系统,其次是我从资产导入的另一个系统。 第二个图像的显示没有填充,并且在fill AspectRatio中,我放置的选项无关紧要。请注意,在使用其他PickerStyle(滚轮)时,它可以完美工作。

我尝试了以下操作:

segmentOptions[1].aspectRatio(contentMode: .fit).padding()
segmentOptions[1].resizable().aspectRatio(contentMode: .fit).padding().frame(width: 20, height: 20, alignment: .center)

以及许多其他组合,但结果仍然相同:第二个图像显示没有填充,并且具有填充AspectRatio。

您对如何解决有任何想法? enter image description here

1 个答案:

答案 0 :(得分:3)

根据发现的结果,我建议将光栅图像的大小显式调整为所需的大小(我使用24 x 24表示1x)...或找到可接受的矢量格式(可能是PDF,但我不确定...试图找到一些要测试的东西,顺便说一句,也可以设计自定义软件)

这就是为什么...让我们从API声明开始

/// A `PickerStyle` where the options are contained in a segmented control.
///
/// - Note: Only supports segments of type `Label` and `Image`. Passing any
/// other type of view will result in a visible, but empty, segment.
@available(iOS 13.0, OSX 10.15, tvOS 13.0, *)
@available(watchOS, unavailable)
public struct SegmentedPickerStyle : PickerStyle {

可以看到,只有Image有效,因此任何sizeToFitaspect都无效,因为它们会生成View。

此处用于手动预先调整大小的PNG图像(任何图形设计人员都可以创建所需大小的完美图像,因为它曾经用于按钮图标)

演示结果:

enter image description here

演示代码:

extension Image {
    static var carFill: Image {
        Image(systemName: "car.fill")
    }

    static var walking: Image {
        Image("pedestrian_small") // < explicitly resized 1x:24 x 24
    }
}

struct TestSegmentWithImages: View {
    @State var selectedIndex = 0

    @State var segmentOptions = [
        Image.carFill,
        Image.walking
    ]

    var body: some View {
        VStack {
            Image("pedestrian") // << original 400 x 400
                .resizable()
                .scaledToFit()
                .frame(width: 48)
            HStack {
                Picker(selection: $selectedIndex, label: Text("")) {
                    segmentOptions[0]
                        .tag(0)
                    segmentOptions[1]
                        .tag(1)
                }.pickerStyle(SegmentedPickerStyle())
                Text("test")
            }
        }
    }

}