具有可选绑定参数的 SwiftUI 视图

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

我正在尝试修改 Stewart Lynch 的 Rating View 以支持框静态表示和设置评级的“控件”。为此,我需要一些可选属性来解决这两种不同的情况。所以

currentRating
是当前评级,用于创建该数量符号的视图。
maxRating
是最大可能的评级 &
mutableRating
是绑定电流额定值,因此我可以将短号值显示为填充符号,直到
maxRating
为止的其余符号未填充,以及未填充并划线的符号以将额定值设置为 0。

我遇到的问题是使绑定参数也是可选的。我发现 this 表明它应该是可能的,但这也相当古老。无论如何,我尝试了注释行中所示的各种排列,试图让初始化工作,但出现了各种不同的失败。

struct RatingView: View {
    var currentRating: Int?
    
    var maxRating: Int?
    @Binding var mutableRating: Int?
    
    var width:Int
    var color: UIColor
    var sfSymbol: String
    
    public init(
        currentRating: Int? = nil,
        maxRating: Int? = nil,
        mutableRating: Binding<Int?>,
//        mutableRating: Binding<Int>?,
//        mutableRating: (Binding<Int>)?,
        width: Int = 20,
        color: UIColor = .systemYellow,
        sfSymbol: String = "star"
    ) {
        self.currentRating = currentRating
        self.maxRating = maxRating
        self._mutableRating = mutableRating
//        self._mutableRating = mutableRating ?? Binding.constant(nil)
        self.width = width
        self.color = color
        self.sfSymbol = sfSymbol
    }
    
    public var body: some View {
        Text("")
    }
}

#Preview ("mutating") {
    struct PreviewWrapper: View {
        @State var rating: Int? = 3
        
        var body: some View {
            RatingView(
                maxRating: 5,
                mutableRating: $rating,
                width: 30,
                color: .red,
                sfSymbol: "heart"
            )
        }
    }
    return PreviewWrapper()
}

#Preview ("non mutating") {
    struct PreviewWrapper: View {
        
        var body: some View {
            RatingView(
                currentRating: 3,
                width: 20,
                color: .red,
                sfSymbol: "heart"
            )
        }
    }
    return PreviewWrapper()
}

所以,我的第一个问题是,我仍然可以在 iOS 17 中执行此操作吗?如果可以,该怎么做? 其次,我很好奇这三种 Init 参数方法之间有什么区别?

mutableRating: Binding<Int?>
mutableRating: Binding<Int>?
mutableRating: (Binding<Int>)?
swift binding optional-parameters
1个回答
0
投票

这是我使用可选绑定的简化解决方案

struct TestView: View {
    @Binding var mutableRating: Int?

    var body: some View {
        TextField("Rating", value: $mutableRating, format: .number.precision(.fractionLength(0)))
            .padding()
    }
}

#Preview {
    return TestView(mutableRating: .constant(42))
}

如果你想使用 init

init(mutableRating: Binding<Int?>) {
    self._mutableRating = mutableRating
}

在 iOS 17.4 和 macOS 14 上测试

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