带有超链接文本的UITextView

Ada*_*son 24 interface-builder swift ios9 xcode8

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

只需点击这里注册

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

我看到我可以使用NSTextCheckingTypeLink,因此在Interface Builder中可以直接获取文本而无需"click here"部分:

只需http://example.com即可注册

我正在使用Xcode 8和Swift 3,如果这是相关的.

Cod*_*ent 42

设置isEditable = false或文本视图将在用户点击时进入文本编辑模式.

斯威夫特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
]
Run Code Online (Sandbox Code Playgroud)

  • 在swift 4中,属性已从NSLinkAttributedName重命名为.link,NSForegroundColorAttributeName重命名为.foregroundColor (3认同)
  • 如果您还没有阅读这个问题,请注意上面示例中的 NSMakeRange(5, 10) 可以解释为从 5 -> 第一个字符 ('c') 的索引到排除的 10 -> 索引的范围最后一个字符(“k”),但这样您可能会收到越界错误。NSMakeRange 实际上需要 5 -> 第一个字符('c')的索引和 10 -> 范围长度。 (3认同)

小智 12

如果你想使用多个超链接,你可以使用这个替代Swift 5

extension UITextView {

  func addHyperLinksToText(originalText: String, hyperLinks: [String: String]) {
    let style = NSMutableParagraphStyle()
    style.alignment = .left
    let attributedOriginalText = NSMutableAttributedString(string: originalText)
    for (hyperLink, urlString) in hyperLinks {
        let linkRange = attributedOriginalText.mutableString.range(of: hyperLink)
        let fullRange = NSRange(location: 0, length: attributedOriginalText.length)
        attributedOriginalText.addAttribute(NSAttributedString.Key.link, value: urlString, range: linkRange)
        attributedOriginalText.addAttribute(NSAttributedString.Key.paragraphStyle, value: style, range: fullRange)
        attributedOriginalText.addAttribute(NSAttributedString.Key.font, value: YourFont, range: fullRange)
    }

    self.linkTextAttributes = [
        NSAttributedString.Key.foregroundColor: YourColor,
        NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue,
    ]
    self.attributedText = attributedOriginalText
  }
}
Run Code Online (Sandbox Code Playgroud)

用法:

yourTextView. addHyperLinksToText(originalText: "Testing hyperlinks here and there", hyperLinks: ["here": "someUrl1", "there": "someUrl2"])
Run Code Online (Sandbox Code Playgroud)


Tej*_*jas 7

使用扩展的Swift 3的相同解决方案:

A.添加扩展名-

extension UITextView {
    func hyperLink(originalText: String, hyperLink: String, urlString: String) {
        let style = NSMutableParagraphStyle()
        style.alignment = .center
        let attributedOriginalText = NSMutableAttributedString(string: originalText)
        let linkRange = attributedOriginalText.mutableString.range(of: hyperLink)
        let fullRange = NSMakeRange(0, attributedOriginalText.length)
        attributedOriginalText.addAttribute(NSLinkAttributeName, value: urlString, range: linkRange)
        attributedOriginalText.addAttribute(NSParagraphStyleAttributeName, value: style, range: fullRange)
        attributedOriginalText.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 10), range: fullRange)
        self.linkTextAttributes = [
            NSForegroundColorAttributeName: UIConfig.primaryColour,
            NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue,
        ]
        self.attributedText = attributedOriginalText
    }
}
Run Code Online (Sandbox Code Playgroud)

B.添加链接网址- let linkUrl = "https://www.my_website.com"

C. UITextViewDelegate像这样在您的ViewController中实现-

 class MyViewController: UIViewController, UITextViewDelegate { 
 }
Run Code Online (Sandbox Code Playgroud)

D.添加委托方法来处理点击事件-

func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
    if (URL.absoluteString == linkUrl) {
        UIApplication.shared.openURL(URL)
    }
    return false
    }
}
Run Code Online (Sandbox Code Playgroud)

E.最后,要确保您的UITextView属性不足检查器的工作-

  1. 行为-可编辑项已关闭,可选项已启用。
  2. 数据检测器-链接已打开。

用法-

textView.hyperLink(originalText: "To find out more please visit our website", hyperLink: "website", urlString: linkUrl)
Run Code Online (Sandbox Code Playgroud)

欢呼与快乐编码!


ela*_*ris 7

Swift 5 这是基于 Tejas 的回答,因为两个类中的一些项目已被弃用。

extension UITextView {


func hyperLink(originalText: String, hyperLink: String, urlString: String) {

    let style = NSMutableParagraphStyle()
    style.alignment = .left

    let attributedOriginalText = NSMutableAttributedString(string: originalText)
    let linkRange = attributedOriginalText.mutableString.range(of: hyperLink)
    let fullRange = NSMakeRange(0, attributedOriginalText.length)
    attributedOriginalText.addAttribute(NSAttributedString.Key.link, value: urlString, range: linkRange)
    attributedOriginalText.addAttribute(NSAttributedString.Key.paragraphStyle, value: style, range: fullRange)
    attributedOriginalText.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.blue, range: fullRange)
    attributedOriginalText.addAttribute(NSAttributedString.Key.font, value: UIFont.systemFont(ofSize: 10), range: fullRange)

    self.linkTextAttributes = [
        kCTForegroundColorAttributeName: UIColor.blue,
        kCTUnderlineStyleAttributeName: NSUnderlineStyle.single.rawValue,
        ] as [NSAttributedString.Key : Any]

    self.attributedText = attributedOriginalText
}
Run Code Online (Sandbox Code Playgroud)

不要忘记将 UITextViewDelegate 添加到您的视图控制器并设置您的 let linkUrl = " https://example.com "

func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
    if (URL.absoluteString == linkUrl) {
        UIApplication.shared.open(URL) { (Bool) in

        }
    }
    return false
}
Run Code Online (Sandbox Code Playgroud)

用法保持不变:

textView.hyperLink(originalText: "To find out more please visit our website", hyperLink: "website", urlString: linkUrl)
Run Code Online (Sandbox Code Playgroud)


Tai*_*sam 6

使用 Swift >= 4:

let descriptionText = NSMutableAttributedString(string:"To learn more, check out our ", attributes: [:])

let linkText = NSMutableAttributedString(string: "Privacy Policy and Terms of Use", attributes: [NSAttributedString.Key.link: URL(string: example.com)!])

descriptionText.append(linkText)
Run Code Online (Sandbox Code Playgroud)


Nor*_*ain 5

斯威夫特 4 代码。 也许我是唯一一个需要在一条消息中设置多个链接并为单词着色的人。我创建了一个 AttribTextHolder 类来累积有关此持有者内文本的所有信息,并轻松在对象之间传递它,以将文本设置到控制器深处的 UITextView 中。

class AttribTextHolder {

        enum AttrType {
            case link
            case color
        }

        let originalText: String
        var attributes: [(text: String, type: AttrType, value: Any)]


        init(text: String, attrs: [(text: String, type: AttrType, value: Any)] = [])
        {
            originalText = text
            attributes = attrs
        }

        func addAttr(_ attr: (text: String, type: AttrType, value: Any)) -> AttribTextHolder {
            attributes.append(attr)
            return self
        }

        func setTo(textView: UITextView)
        {
            let style = NSMutableParagraphStyle()
            style.alignment = .left

            let attributedOriginalText = NSMutableAttributedString(string: originalText)

            for item in attributes {
                let arange = attributedOriginalText.mutableString.range(of: item.text)
                switch item.type {
                case .link:
                    attributedOriginalText.addAttribute(NSAttributedString.Key.link, value: item.value, range: arange)
                case .color:
                    var color = UIColor.black
                    if let c = item.value as? UIColor { color = c }
                    else if let s = item.value as? String { color = s.color() }
                    attributedOriginalText.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: arange)
                default:
                    break
                }
            }

            let fullRange = NSMakeRange(0, attributedOriginalText.length)
            attributedOriginalText.addAttribute(NSAttributedString.Key.paragraphStyle, value: style, range: fullRange)

            textView.linkTextAttributes = [
                kCTForegroundColorAttributeName: UIColor.blue,
                kCTUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue,
            ] as [String : Any]

            textView.attributedText = attributedOriginalText
        }
 }
Run Code Online (Sandbox Code Playgroud)

像这样使用它:

 let txt = AttribTextHolder(text: "To find out more visit our website or email us your questions")
            .addAttr((text: "our website", type: .link, "http://example.com"))
            .addAttr((text: "our website", type: .color, "#33BB22"))
            .addAttr((text: "email us", type: .link, "mailto:us@example.com"))
            .addAttr((text: "email us", type: .color, UIColor.red))
 ....
 ....
 txt.setTo(textView: myUITextView)
Run Code Online (Sandbox Code Playgroud)

另外,在此代码中,我使用简单的 String 扩展将 String 十六进制值转换为 UIColor 对象

extension String {
/// Converts string color (ex: #23FF33) into UIColor
func color() -> UIColor {
    let hex = self.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
    var int = UInt32()
    Scanner(string: hex).scanHexInt32(&int)
    let a, r, g, b: UInt32
    switch hex.characters.count {
    case 3: // RGB (12-bit)
        (a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
    case 6: // RGB (24-bit)
        (a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
    case 8: // ARGB (32-bit)
        (a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
    default:
        (a, r, g, b) = (255, 0, 0, 0)
    }
    return UIColor(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255)
  }
}
Run Code Online (Sandbox Code Playgroud)