我在SwiftUI Badge中发现了一个bug,它不会工作,只要它是嵌套的。虽然这是测试版的新功能,但是原因是什么呢?为什么不能使用嵌套?如能解决,将不胜感激。
以下代码一种是标识在外层使用,另一种是标识未在外层使用。结果是一个不显示正确的文本,而另一个显示正确的文本。
嵌套效果没有嵌套的
TabView {
NavigationView {
TextBadgeList()
}
.tabItem {
Image(systemName: "rectangle.and.pencil.and.ellipsis")
}
.tag(1)
.badge(99)
NavigationView {
TextBadgeList()
}
.tabItem {
Image(systemName: "pencil.and.outline")
}
.tag(2)
}
.frame(height: 300)
TextBadgeList
List {
Section {
VStack {
Text("wi-fi")
Text("No")
}
.badge("LAN Solo")
Text("wi-fi")
.badge("LAN Solo")
Text("wi-fi")
.badge(900)
}
}
这可能是一个bug。请向Apple报告
https://developer.apple.com/bug-reporting/
https://developer.apple.com/news/?id=vvrgkboh
这是一个解决方案。
徽章仅在list rows
和iOS tab bars
中显示。如果在列表行中使用,则以辅助颜色显示为右对齐文本。
创建一个自定义的ViewModifier
并在列表行中使用。
struct CustomBudge: ViewModifier {
let text: Text
func body(content: Content) -> some View {
HStack {
content
Spacer()
text.foregroundColor(Color.secondary)
}
}
}
extension View {
func customBudge(_ s: String) -> some View {
self.modifier(CustomBudge(text: Text(s)))
}
func customBudge(_ number: Int) -> some View {
self.modifier(CustomBudge(text: Text("(number)")))
}
func customBudge(_ text: Text) -> some View {
self.modifier(CustomBudge(text: text))
}
}
就像这样用
struct TextBadgeList2: View {
var body: some View {
List {
Section {
VStack {
Text("wi-fi")
Text("No")
}
.customBudge("LAN Solo")
Text("wi-fi").customBudge("LAN Solo")
Text("wi-fi").customBudge(900)
Text("Text Budge ").customBudge(Text("test"))
}.id(UUID())
}
}
}