如何从Swift中的UITextView获取链接范围 [英] How to get links ranges from UITextView in Swift
问题描述
我有一个聊天应用程序,其中带有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:
- 地址链接未使用
tintColor
或linkTextAttributes
属性中的颜色进行着色,也未使用appearance()
代理进行着色. - 默认情况下,所有链接都带有下划线.
- 某些链接的颜色正确,但是我看不到为什么某些链接被省略的模式(看起来可能与自动换行有关).
- 设置自定义
underlineStyle
属性时,文本只会消失.
- The address links are not colored with the
tintColor
or with the color fromlinkTextAttributes
property, or using theappearance()
proxy. - All of the links are underlined by default.
- 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).
- 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屋!