如何从Swift中的UITextView获取链接范围 [英] How to get links ranges from UITextView in Swift

查看:119
本文介绍了如何从Swift中的UITextView获取链接范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个聊天应用程序,其中带有UITextView的动态文本(来自服务器或由用户键入).我需要检测所有类型的链接,而UITextView在检测电话号码,地址,超链接和日历事件方面做得很好. UITextView不足之处是样式,那里存在多个问题:

I have a chat app with the UITextView with a dynamic text (comes from the server or is typed by the user). I needed to detect all types of links, and the UITextView does a great job in detecting phone numbers, addresses, hyperlinks and calendar events. Where UITextView falls short is styling, there are multiple problems there:

  1. 地址链接未使用tintColorlinkTextAttributes属性中的颜色进行着色,也未使用appearance()代理进行着色.
  2. 默认情况下,所有链接都带有下划线.
  3. 某些链接的颜色正确,但是我看不到为什么某些链接被省略的模式(看起来可能与自动换行有关).
  4. 设置自定义underlineStyle属性时,文本只会消失.
  1. The address links are not colored with the tintColor or with the color from linkTextAttributes property, or using the appearance() proxy.
  2. All of the links are underlined by default.
  3. Some of the links are colored properly, but I fail to see a pattern why certain links are omitted (looks like it may have something to do with the word wrap).
  4. When setting custom underlineStyle attribute, the text simply disappears.

因此,我认为最好的方法是仍然使用UITextView来检测链接,然后创建自己的属性字符串并按所需方式设置所有样式.为此,我需要链接的范围,但是找不到找到它们的方法.

So I thought the best thing to do would be to still use the UITextView for detecting the links, but then create my own attributed string and style everything the way I want. For this I need the ranges for the links, but I can't find the way to get them.

我尝试过:

open func enumerateAttributes(in enumerationRange: NSRange, options opts: NSAttributedString.EnumerationOptions = [], using block: ([NSAttributedString.Key : Any], NSRange, UnsafeMutablePointer<ObjCBool>) -> Void)

但是从来没有任何.link元素,也没有任何下划线属性(如果我要寻找的话).所以问题是,是否有办法以某种方式从UITextView获取链接范围?也许有一种方法可以可靠地设置我丢失的链接的样式?

But there are never any .link elements, nor any underline attributes if I look for them. So the question is, is there a way to get the link ranges from the UITextView somehow? Or perhaps there is a way to reliably style the links that I'm missing?

推荐答案

要检测电话号码,地址等,实际上您正在使用

To detect the Phone Numbers, addresses etc, you are in fact using the NSDataDetector.

您实际上是在InterfaceBuilder中设置的:

That's what you in fact set in InterfaceBuilder there:

然后:

let types: NSTextCheckingResult.CheckingType = [.address, .link, .phoneNumber, .date]
let detector = try? NSDataDetector(types: types.rawValue)
let matches = detector.matches(in: text, options: [], range: NSRange(location: 0, length: text.utf16.count))
matches.forEach {
    guard let range = Range($0.range, in: text) else { return }
    let sub = String(text[range])
    print(sub)
}

这篇关于如何从Swift中的UITextView获取链接范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆