swift - Xcode 产生“分段错误:11”编译
问题描述
编译以下代码时,Xcode 版本 11.3.1 (11C504) 会抛出:
“错误:分段错误:11(在项目 'TestDel3' 的目标 'TestDel3' 中)”
如果我注释掉Image(systemName: systemName)
并用它替换Image(systemName: "person")
它编译
struct ContentView: View{
var body: some View {
UseButtonContainer( b: ButtonContainer("x1",systemName:"person") {print("c1")})
}
}
struct UseButtonContainer: View{
let b : ButtonContainer
var body: some View {
Button(action: {
self.b.action();
self.extraAction()
}) { b.label}
}
func extraAction()->Void{
print("extra action")
}
}
struct ButtonContainer{
let label: VStack<TupleView<(Image, Text)>>
let action: ()-> Void
init(_ text: String, systemName: String, action: @escaping ()-> Void){
self.label = VStack{
Image(systemName: systemName) // Commenting out this line
//Image(systemName: "person") // and using this instead, it compiles
Text(text)
}
self.action = action
}
}
What's wrong here?
解决方案
更新:以下变体有效
struct ButtonContainer{
let label: VStack<TupleView<(Image, Text)>>
let action: ()-> Void
init(_ text: String, systemName: String, action: @escaping ()-> Void){
self.label = VStack {
Image(systemName: "\(systemName)") // << make it string literal !!!
Text(text)
}
self.action = action
}
}
初始(以防万一):
考虑到 SwiftUI 几乎在所有地方都使用不透明类型some View
,使用擦除类型进行label
编译和运行良好的方法(使用 Xcode 11.3.1 / iOS 13.3 测试)。我不确定您是否需要在这里使用显式类型,但请注意。
struct ButtonContainer{
let label: AnyView
let action: ()-> Void
init(_ text: String, systemName: String, action: @escaping ()-> Void){
self.label = AnyView(VStack {
Image(systemName: systemName)
Text(text)
})
self.action = action
}
}
推荐阅读
- python - CentOS 中 Python 不采用 GCC 的更新版本
- android - google 制作的 Android 库的名称是什么?
- java - 片段中的Android后退按钮导致崩溃
- c# - 如何从json中的不同类中获取数据值?例如使用其 id 的名称
- kubernetes - Istio:RequestAuthentication jwksUri 不解析内部服务名称
- python - 在python中迭代一个目录以知道该目录中有多少“PXXX”目录
- javascript - 如何将两个 JavaScript 合二为一以使用 if 条件?
- ubuntu - 如何让 Plesk 调整分区大小。未检测到硬件更改
- python - 导入“pytube”无法解决 pylance (repotMissingImport)
- android - 在 OnClickListener 中查看未更新