适用于 iOS 15 及更高版本的更新:
对Text 有新的Markdown 格式支持,如:
Text("Some text [clickable subtext](some url) *italic ending* ")
详情可查看WWDC session with a timecode
iOS 13 和 14 的旧答案:
不幸的是,SwiftUI 中没有任何类似于 NSAttributedString 的东西。你只有几个选择。 In this answer 你可以看到如何使用UIViewRepresentable 来创建一个老式的UILabel with click event,例如。但是now the only SwiftUI way是用HStack:
struct TappablePieceOfText: View {
var body: some View {
HStack(spacing: 0) {
Text("Go to ")
.foregroundColor(.gray)
Text("stack overflow")
.foregroundColor(.blue)
.underline()
.onTapGesture {
let url = URL.init(string: "https://stackoverflow.com/")
guard let stackOverflowURL = url, UIApplication.shared.canOpenURL(stackOverflowURL) else { return }
UIApplication.shared.open(stackOverflowURL)
}
Text(" and enjoy")
.foregroundColor(.gray)
}
}
}
更新
添加了UITextView 和UIViewRepresentable 的解决方案。我将添加的链接中的所有内容结合起来,我认为结果非常好:
import SwiftUI
import UIKit
struct TappablePieceOfText: View {
var body: some View {
TextLabelWithHyperlink()
.frame(width: 300, height: 110)
}
}
struct TextLabelWithHyperlink: UIViewRepresentable {
func makeUIView(context: Context) -> UITextView {
let standartTextAttributes: [NSAttributedString.Key : Any] = [
NSAttributedString.Key.font: UIFont.systemFont(ofSize: 20),
NSAttributedString.Key.foregroundColor: UIColor.gray
]
let attributedText = NSMutableAttributedString(string: "You can go to ")
attributedText.addAttributes(standartTextAttributes, range: attributedText.range) // check extention
let hyperlinkTextAttributes: [NSAttributedString.Key : Any] = [
NSAttributedString.Key.font: UIFont.systemFont(ofSize: 20),
NSAttributedString.Key.foregroundColor: UIColor.blue,
NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue,
NSAttributedString.Key.link: "https://stackoverflow.com"
]
let textWithHyperlink = NSMutableAttributedString(string: "stack overflow site")
textWithHyperlink.addAttributes(hyperlinkTextAttributes, range: textWithHyperlink.range)
attributedText.append(textWithHyperlink)
let endOfAttrString = NSMutableAttributedString(string: " end enjoy it using old-school UITextView and UIViewRepresentable")
endOfAttrString.addAttributes(standartTextAttributes, range: endOfAttrString.range)
attributedText.append(endOfAttrString)
let textView = UITextView()
textView.attributedText = attributedText
textView.isEditable = false
textView.textAlignment = .center
textView.isSelectable = true
return textView
}
func updateUIView(_ uiView: UITextView, context: Context) {}
}
HStack 和 Text 的结果:
UIViewRepresentable 和 UITextView 的结果:
更新 2:
这是一个NSMutableAttributedString 的小扩展:
extension NSMutableAttributedString {
var range: NSRange {
NSRange(location: 0, length: self.length)
}
}