SwiftUI behavior of .frame(height: nil)

前端 未结 2 1964
既然无缘
既然无缘 2021-01-22 00:44

The issue

I\'m getting a thread issue that says "Invalid frame dimension (negative or non-finite)."

Here\'s my code:

struct CellSty         


        
相关标签:
2条回答
  • 2021-01-22 00:45

    Because it is documented interface contract:

    /// - Parameters:
    ///   - width: A fixed width for the resulting view. If `width` is `nil`,
    ///     the resulting view assumes this view's sizing behavior.
    ///   - height: A fixed height for the resulting view. If `height` is `nil`,
    ///     the resulting view assumes this view's sizing behavior.
    ///   - alignment: The alignment of this view inside the resulting view.
    ///     `alignment` applies if this view is smaller than the size given by
    ///     the resulting frame.
    ///
    /// - Returns: A view with fixed dimensions of `width` and `height`, for the
    ///   parameters that are non-`nil`.
    @inlinable public func frame(width: CGFloat? = nil, height: CGFloat? = nil, alignment: Alignment = .center) -> some View
    

    whereas modifier type with min/max arguments allows flexible constraints (not copied here - read in generated SwiftUI module).

    0 讨论(0)
  • 2021-01-22 01:12

    What .frame(width: nil) does

    Basically .frame will take the given values and return another view that is updated with the values you put.
    If you omit one of the parameters or set it to nil, then it will take the respective width/height value of the previous view.

    Test code:

    struct ContentView: View {
        @State var keyValue = ""
        var body: some View {
            VStack(spacing: 10) {
                Text("Something")
                    .background(Color.blue)
                
                Text("Something")
                    .frame(width: 300, height: nil, alignment: .center)
                    .background(Color.blue)
                
                Text("Something")
                    .frame(width: nil, height: 200, alignment: .center)
                    .background(Color.blue)
                
                Text("Something")
                    .frame(width: nil, height: nil, alignment: .center)
                    .background(Color.blue)
            }
        }
    }
    

    Why .frame(width: .infinity) still runs

    .infinity (Apple doc on .infinity) is of type Float, so there's no way for .frame not to except it, but it still can create problems. (Thus the thread issue)

    Thanks to Mark Moeykens for the help in getting me to this answer!

    0 讨论(0)
提交回复
热议问题