在Apple SwiftUI Tutorial: Drawing Paths and Shapes上,显示以下语法:
struct Badge: View {
var body: some View {
GeometryReader { geometry in
Path { path in
...
}
.fill(Color.black)
}
}
}
我在Swift docs on structs中没有看到语法,感到非常困惑。
另外,人们怎么会知道geometry
在GeometryReader
语句中,无论意味着什么?
Path { path in
...
}
与...相同
Path( { (path) in ... })
使用的Path
构造函数
/// Initializes to an empty path then calls `callback` to add /// the initial elements. public init(_ callback: (inout Path) -> ())
顺便说一下,此语法已在SwiftUI中广泛使用,因此您将在SwfitUI框架的VStack { .. }
,GeometryReader { g in ... }
,ScrollView { ... }
和几乎所有其他UI元素中看到相同的语法。
in
之前的变量名称是闭包的输入参数。在SwiftUI的上下文中,该闭包实际上是一个ViewBuilder
,它是函数构建器的一种特定类型。您可以阅读有关函数阅读器和其他使SwiftUI成为可能的其他语法糖的更多信息ViewBuilder
。
您可以通过选择在Xcode中单击闭包输入参数的类型来学习闭包输入参数的类型,就像其他任何变量一样。或者,您可以查看here的文档以了解其闭包接受哪些输入参数。