[英]How to underline a substring in a Text in SwiftUI?
Text(..)
視圖有一個組合文本的+
運算符。 還沒有看過這個魔法是如何工作的,但它確實做得很好。
Text("Regular text... ")
+ Text("underlined text!")
.underline()
還有第二種方法是在字符串上使用帶underlined()
function:
Text("Regular text... " + "undelined text!".underlined())
超酷!
對我有用的是將字符串插值與其他文本對象一起使用。
例如
Text("This sentence is not underlined. \(Text("But this sentence is underlined.").underline())")
使用這種策略,我能夠在原始文本 object 中插入三個不同的帶下划線的文本對象,而編譯器不會抱怨。
希望這可以幫助!
有幾種方法可以實現它。 我會提到使用 AttributedString()
func getAttributedString(string: String) -> AttributedString {
var attributedString = AttributedString(string)
attributedString.font = .body.bold()
attributedString.underlineStyle = .single
return attributedString
}
在這里,在 function 中,我還添加了粗體和下划線,您可以添加更多 styles。這可以保留在 ViewModel class 中,並像這樣從 View 調用:
Text("You must be invited by an...." + model. getAttributedString(string: "apply to be on the waitlist"))
或者還有另一種方法,您可以在 ViewModel 中創建另一個 function 來執行我在上面顯示的內容。
Text(model.getString()) // put this in View
func getString() -> AttributedString {
return "You must be invited by an...." + getAttributedString(string: "apply to be on the waitlist")
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.