[英]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.