SwiftUI 视图和 Swift 包管理器
我正在尝试创建一个基本上是单个 SwiftUI 视图的 Swift 包.我在这里创建了一个示例来显示正在发生的事情.打包做什么,并不重要,我只是在视图中包含了一些 @State 和 @Binding 变量,这样我就会得到与我在真实包中得到的相同的错误.视图结构是这样的.
I am trying to create a Swift Package that is basically a single SwiftUI View. I have created a sample here to display what is happening. What the packaged does, doesn't matter, I have just included some @State and @Binding variables in the View so that I get the same error I get in my real package. The View struct is this.
import SwiftUI
public struct SampleView: View {
@Binding var myNum:Int
@State var fixedText:String = ""
var myText = ""
var optional: String?
public var body: some View {
VStack {
if optional != nil {
Text(optional!)
}
Text(myText)
Text("Parent number: \(myNum)")
Text("\(fixedText)")
Button("Increment num") {
self.myNum += 1
}.foregroundColor(.blue)
Button("Change Parent Text") {
self.fixedText = "Only Changes Child"
}.foregroundColor(.blue)
}.background(Color.red)
.foregroundColor(.white)
}
}
当我添加包并将其导入到我的项目中的一个视图中时,如果视图不是 Swift 包的一部分,我应该能够像这样使用 Do like this:
When I add the package and import it into one of the views in my project, I should be able to use Do something like this as I can do if the View is not part of a Swift Package:
SampleView(myNum: $myNum,
fixedText: parentText,
myText: "Display Text Passed from parent")
但是,我没有得到代码完成并且出现错误:
However, I get no code completion and I get the error:
'SampleView' initializer is inaccessible due to 'internal' protection level
我在 SampeView 结构上尝试了各种初始化,但不断收到各种不同的错误.我只是不明白如何在这里修复访问级别.任何人都可以帮忙吗?截图也在这里.
I have tried all sorts of initializations on the SampeView struct, but keep getting all sorts of different errors. I just don't understand how to fix the access levels here. Can anyone help? Screenshot is here also.
这里是 Package 中的预期声明(使用 Xcode 11.2.1/iOS 13.2.2 测试).请注意,@State
不允许在 View 之外使用,因此您需要同步的所有内容都应通过 Binding
传递:
Here is expected declaration in Package (tested with Xcode 11.2.1 / iOS 13.2.2). Please note that @State
are not allowed to be used outside of View, so all you need to make in sync should be passed via Binding
:
public struct SampleView: View {
@Binding var myNum:Int
@Binding var fixedText:String
var myText: String
var optional: String?
public init(myNum: Binding<Int>, fixedText: Binding<String>,
myText: String = "", optional: String? = nil) {
self._myNum = myNum
self._fixedText = fixedText
self.myText = myText
self.optional = optional
}
public var body: some View {
VStack {
if optional != nil {
Text(optional!)
}
Text(myText)
Text("Parent number: \(myNum)")
Text("\(fixedText)")
Button("Increment num") {
self.myNum += 1
}.foregroundColor(.blue)
Button("Change Parent Text") {
self.fixedText = "Only Changes Child"
}.foregroundColor(.blue)
}.background(Color.red)
.foregroundColor(.white)
}
}
和用法:
@State private var myNum: Int = 1
@State private var parentText = "Test"
var body: some View {
SampleView(myNum: $myNum,
fixedText: $parentText,
myText: "Display Text Passed from parent")
}