我有一个 SwiftUI 可扩展的常见问题解答 View ,其中包含我想要粗体的问题文本和我想要保留为非粗体文本的答案文本。
我只能将两者都设置为粗体或将常规粗细设置为粗体,但想知道是否可以选择性地将问题文本仅设置为粗体?
下面是我到目前为止所拥有的代码和屏幕截图。
常见问题解答查看
struct FAQ: View {
let questionItems : [QuestionAnswer] = [ qa1(), qa2(), qa3() ]
var body: some View {
VStack {
List(questionItems, children: \.textTwo) { item in
Text(item.textOne)
//.bold() makes BOTH bold or regular without
.padding([.top, .bottom], 15)
}
.foregroundColor(.black)
.clipped()
}
.navigationBarTitle("Frequently asked questions", displayMode: .inline)
.navigationBarBackButtonHidden(true)
}
}
func qa1() -> QuestionAnswer {
return .init(textOne: "Question one", textTwo: [.init(textOne: "Answer one")])
}
func qa2() -> QuestionAnswer {
return .init(textOne: "Question two", textTwo: [.init(textOne: "Answer two")])
}
func qa3() -> QuestionAnswer {
return .init(textOne: "Question three", textTwo: [.init(textOne: "Answer three")])
}
数据模型
struct QuestionAnswer: Identifiable {
let id = UUID()
let textOne: String
var textTwo: [QuestionAnswer]?
}
最佳答案
您可以检查一行是否有任何子行来决定是否将文本加粗。
List(questionItems, children: \.textTwo) { item in
if item.hasChildren {
Text(item.textOne)
.bold()
.padding([.top, .bottom], 15)
} else {
Text(item.textOne)
.padding([.top, .bottom], 15)
}
}
extension QuestionAnswer {
var hasChildren: Bool { !(textTwo?.isEmpty == true) }
}
或者使用评论中建议的方法
List(questionItems, children: \.textTwo) { item in
Text(item.hasChildren ? "**\(item.textOne)**" : item.textOne )
.padding([.top, .bottom], 15)
}
关于ios - 是否可以将 SwiftUI 列表项文本选择性地设置为常见问题解答部分的粗体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72759595/