
在使用Xcode编写SwiftUI代码时,一个小小的疏忽会导致代码编译通过,但预览界面发生崩溃的情况。
下面,我们就来看一下到底是怎么回事吧。
首先,来看一下源代码:
ZStack(alignment: .trailing){
HStack {
VStack {
Text(Model.shortDateFt.string(from: st.date ?? Date.distantPast))
.fontWeight(.light)
.font(.footnote)
.foregroundColor(.slateGray)
CommonUI.hiveScoringTracesView(st, model: model)
}.frame(minWidth: 65.0)
stateView
.foregroundColor(stateColor)
.frame(minWidth: 30)
HStack(alignment: .top) {
Text("\(st.totalGainedScore)")
.fontWeight(.heavy)
.font(.body)
.foregroundColor(scoreColor)
.opacity(1.0)
baseScoreView
.underline(true, color: stateColor)
.fontWeight(.bold)
.font(.callout)
.foregroundColor(stateColor)
}.frame(minWidth: 50)
HStack {
Text("\(st.sumOfSubScore)")
.fontWeight(.bold)
.foregroundColor(.mediumPurple)
.frame(minWidth: 30)
Text("\(st.ibAddUp)")
.fontWeight(.bold)
.foregroundColor(.green)
.frame(minWidth: 30)
Text("\(st.ipSubtract)")
.fontWeight(.bold)
.foregroundColor(.red)
.frame(minWidth: 30)
Text("\(st.igbAddUp)")
.fontWeight(.bold)
.foregroundColor(.green)
.frame(minWidth: 30)
}
.opacity(0.5)
font(.callout)
if st.hasRemarks{
Button(action: {
withAnimation {
self.isUnfoldRemarks.toggle()
}
}){
Image(systemName: isUnfoldRemarks ? "arrowtriangle.down.square.fill" : "arrowtriangle.down.square")
.foregroundColor(.deepSkyBlue)
.font(.system(size: 13, weight: .bold))
.offset(x: 15)
}
.buttonStyle(BorderlessButtonStyle())
}
}
}
上面代码可以顺利通过编译,但会导致Xcode预览崩溃:

喜欢玩“大家来找茬”的小伙伴们可以先尝试找一下是哪里的问题… 😉
看出问题在哪了吗?
问题就在于其中一行代码里font()方法前面少了一个点:
font(.callout)
我们的本意是在前面HStack视图上应用字体修改器方法,结果少打了一个点。
这样默认行为会在self上调用font()方法,那么self是什么呢?
self就是根视图本身!
比如,下面self代表的就是MainView视图本身:
struct MainView: View {
var body: some View {
VStack {
Text("hello world")
font(.title) // 等同于 self.font(.title)
}
.padding()
.frame(width: 200, height: 300)
}
}
所以,这样写从语法上来说是没问题的,这就是为什么编译可以通过,但预览会崩溃的原因了。
有了上面的教训,我们下次在Xcode预览发生崩溃不知所措的时候,记得提醒自己别忘写了那个小小的点哦?😎
感谢观赏,下次再会!