🧸
大家好!欢迎来到我的迷你库许多应用界面都包含带有链接的文本。因此,为了易于实现,这个库被制作出来,以提供一个配置自您的 UITextView
中的格式化的 NSMutableAttributedString
。
以下是步骤分解:
- 在 Podfile 中添加此行并运行
pod install
pod 'AttributedTextURL', '~> 0.0.4'
- 创建一个
UITextView
,例如:
private lazy var textView: UITextView = {
let text = UITextView()
text.isEditable = false
text.isSelectable = true
text.isScrollEnabled = false
text.translatesAutoresizingMaskIntoConstraints = false
return text
}()
- 在
viewDidLoad
中,设置文本视图代理和链接文本属性
textView.delegate = self
textView.linkTextAttributes = [ * your link attributes here, for style * ]
- 让您的
UIViewController
实现UITextViewDelegate
并导入SafariServices
extension ViewController: UITextViewDelegate {
func textView(
_ textView: UITextView,
shouldInteractWith URL: URL,
in characterRange: NSRange,
interaction: UITextItemInteraction
) -> Bool {
let safariViewController = SFSafariViewController(url: URL)
present(safariViewController, animated: true)
return false
}
}
- 以下是库的用法。 在
viewDidLoad
中,调用一个将配置您的UITextView
参数的方法
func setupAttributedText() {
let attributedText = AttributedTextWithURLHelper.getAttributedStringWithSingleURL(
text: * your full text here, but with `%@` where your link is going to be *,
styleAttributes: [ * your full text attributes here, for style * ],
link: LinkInfo(text: * your link text here *, urlAddress: * your url address here *)
)
textView.attributedText = attributedText
}
就这么简单!
有疑问?这里有一个用法示例:[点击查看](https://github.com/dejacs/AttributedTextURL/tree/main/AttributedTextURLExamples/Example)
您还可以在此处联系我:[点击查看](https://twitter.com/Mockada)
希望您会喜欢它
CocoaPods 链接:[点击查看](https://cocoapods.org.cn/pods/AttributedTextURL)