swift - 带有超链接文本的 UITextView

标签 swift interface-builder ios9 xcode8

使用不可编辑的 UITextView,我想在 iOS9+ 中嵌入这样的文本:

Just click here to register

我可以创建一个函数并操作文本,但是有更简单的方法吗?

我发现我可以使用 NSTextCheckingTypeLink,因此在 Interface Builder 中让文本可点击而无需“单击此处”部分是很简单的:

Just http://example.com to register

如果相关的话,我正在使用 Xcode 8 和 Swift 3。

最佳答案

设置isEditable = false,否则当用户点击 TextView 时, TextView 将进入文本编辑模式。

Swift 4 及更高版本

let attributedString = NSMutableAttributedString(string: "Just click here to register")
let url = URL(string: "https://www.apple.com")!

// Set the 'click here' substring to be the link
attributedString.setAttributes([.link: url], range: NSMakeRange(5, 10))

self.textView.attributedText = attributedString
self.textView.isUserInteractionEnabled = true
self.textView.isEditable = false

// Set how links should appear: blue and underlined
self.textView.linkTextAttributes = [
    .foregroundColor: UIColor.blue,
    .underlineStyle: NSUnderlineStyle.single.rawValue
]

关于swift - 带有超链接文本的 UITextView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56875213/

相关文章:

ios - 当 TableView 单元格被选择两次时,它会崩溃并出现意外的 nil 错误

ios - 在 IOS Swift 中,如何使白色文本在任何背景上都可见,就像在 snapchat 故事中一样

ios - 检测 UITableView 下面的 UIPageView 上的滑动事件

ios - UIScrollView 与 UITabBarController 切断

ios - 为什么 UIBarButtonItems 最小尺寸时宽度为 0

ios9 - 启用位码 Xcode 7.1

objective-c - 以编程方式列出 iOS 设备中安装的所有应用程序的版本

ios - 检查 JSON 对象是否为 null swift 3

cocoa - 我如何在自定义类中创建 `IBOutlet` 或 `IBAction`

ios - Xcode UITest 记录按钮被禁用