SwiftUI Picker SegmentedStyle图像显示错误

问题描述 投票:0回答:1

我在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

swift image swiftui uisegmentedcontrol picker
1个回答
0
投票

根据我的发现,我建议将光栅图像的大小显式调整为所需的大小(我使用24 x 24)...或找到可接受的矢量格式(可能是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图像(任何图形设计人员都可以创建所需大小的完美图像,因为它曾经用于按钮图标)

演示结果:

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9yOHFkbS5wbmcifQ==” alt =“在此处输入图像描述”>

演示代码:

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

    static var walking: Image {
        Image("pedestrian_small") // < explicitly resized 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")
            }
        }
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.