如图,需要对字符串中部分字符改变颜色和字体。
在 SwiftUI 中合并带有不同样式的文本,应该使用不同的 Text
实例并将它们合并起来。将实例使用 +
运算符合并起来,每个 Text
实例都保持其自己的样式设置。这种方式可以正常编译并运行,同时支持文本换行。
示例如下:
import SwiftUI
struct ContentView: View {
var body: some View {
VStack {
let priceText: String = "Free trial for 3 days, then $4.99 per week"
let restOfTheText = "Humans are part of nature and we follow the laws of the universe to find the meaning of life "
let subscriptionInfo = ". Subscription automatically renews unless auto-renew is turned off at least 24-hours before the end of the current period. Subscriptions can be managed and auto-renewal can be turned off in Account Settings in iTunes after the purchase."
Text(restOfTheText)
.font(.system(size: 13))
.foregroundColor(Color.gray)
+
Text(priceText)
.font(.system(size: 15))
.fontWeight(.bold)
.foregroundColor(Color.white)
+
Text(subscriptionInfo)
.font(.system(size: 13))
.foregroundColor(Color.gray)
}
.frame(maxWidth: .infinity, alignment: .center)
.multilineTextAlignment(.center)
.padding(.horizontal, 25)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}