按钮构造函数似乎不允许局部变量

为什么此代码无法编译? 它说“无法推断出通用参数'标签'”

struct ReadyToEatListX: View {
  var body : some View{
    Button(action: {}){
      let text = "Hello, World"  
      return Text(text)
    }
  }
}
评论
陌若惜
陌若惜

You cannot have a variable inside the body as it is expecting a View.

@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
public struct Button<Label> : View where Label : View {

    /// Creates an instance for triggering `action`.
    ///
    /// - Parameters:
    ///     - action: The action to perform when `self` is triggered.
    ///     - label: A view that describes the effect of calling `action`.
    public init(action: @escaping () -> Void, @ViewBuilder label: () -> Label)

    /// Declares the content and behavior of this view.
    public var body: some View { get }

    /// The type of view representing the body of this view.
    ///
    /// When you create a custom view, Swift infers this type from your
    /// implementation of the required `body` property.
    public typealias Body = some View
}

但是,您可以在视图之外使用局部变量。

struct ReadyToEatListX: View {
    var bodyText = "Hello, World"

    var body : some View{
        Button(action: {}){
            Text(bodyText)
        }
    }
}
点赞
评论
埋葬那份爱
埋葬那份爱

这是固定的变体,仅帮助编译器了解Label提供的类型

struct ReadyToEatListX: View {
  var body : some View {
    Button(action: {}) { () -> Text in // << here !!
      let text = "Hello, World"
      return Text(text)
    }
  }
}
点赞
评论