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 将在用户点击时进入文本编辑模式。

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/39238366/

相关文章:

ios - NSFileManager:无法在某些设备上创建目录

objective-c - 如何填充数组并同时查看其数据 - Swift - IOS9

swift - 无法在 Xcode 中导入包

Swift 包 : error: product dependency 'LineNoise' in package 'linenoise-swift' not found

XCode:编译XIB时Interface Builder崩溃

ios - 如何在界面生成器中正确约束图像

ios - 如何在 Interface Builder 中使用自定义 UIButton 类别?

ios - UIViewController 容器不显示 ChildViewController

ios - 安装 Swift 开源 Xcode 工具链时出错 : You cannot install Swift Open Source Xcode Toolchain in this location

swift2 - Swift 2 中的排序函数