[英]Is it possible to make SwiftUI List item text selectively bold for FAQ section?
我有一个 SwiftUI 可扩展的常见问题解答视图,其中包含我想要粗体的问题文本和我想要保留为非粗体文本的答案文本。
我只能将两者都设置为粗体或常规权重,但想知道是否可以选择性地将问题文本仅设置为粗体?
下面是我到目前为止的代码和屏幕截图。
常见问题 查看
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)
}
您可以在此处的文档中使用此技巧: https ://developer.apple.com/documentation/swiftui/list
struct FileItem: Hashable, Identifiable, CustomStringConvertible {
var id: Self { self }
var name: String
var children: [FileItem]? = nil
var description: String {
switch children {
case nil:
return "📄 \(name)"
case .some(let children):
return children.isEmpty ? "📂 \(name)" : "📁 \(name)"
}
}
}
除了在描述中更改图标之外,您还可以添加@Joakim Danielson 建议的**
您可以做的另一种方法是低于一个
var body: some View {
VStack{
List{
ForEach(questionItems) { item in
DisclosureGroup {
ForEach(item.textTwo ?? [QuestionAnswer]()) { innterItem in
Text(innterItem.textOne)
}
} label : {
Text(item.textOne)
.bold()
}
}
}
.foregroundColor(.black)
.clipped()
}
.navigationBarTitle("Frequently asked questions", displayMode: .inline)
.navigationBarBackButtonHidden(true)
}
您可以使用属性字符串。
extension Text {
init(_ string: String, configure: ((inout AttributedString) -> Void)) {
var attributedString = AttributedString(string)
configure(&attributedString)
self.init(attributedString) // Text initialization
}
}
用法:
Text("Your Text") { string in
string.foregroundColor = .Color
if let range = string.range(of: "Attributed") {
string[range].foregroundColor = .YourColor // Use Your Style
}
}
在您需要的任何地方使用。 对于您当前的问题,请在列表中使用属性字符串。 你可以尽可能地设计。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.