在UITextView中与空格建立链接 - iOS Swift

时间:2016-09-26 16:55:28

标签: swift hyperlink uitextview nsmutableattributedstring

我有一个带有可点击链接的UITextView。链接是通过在文本中搜索placesArray中包含的某些单词或短语来创建的,如下所示:

for place in placesArray {
    let range = (text as NSString).range(of: place)
    attributedText.addAttribute(NSFontAttributeName, value: UIFont(name:"Helvetica-Bold", size:16.0)!, range: range)
    attributedText.addAttribute(NSLinkAttributeName, value: place, range: range)
}

一切正常,除非链接是根据其中包含空格的短语创建的,例如"加利利海"。当我单击此链接时,应用程序崩溃。调试窗口中没有显示任何内容,但我确实看到了"线程1:EXC_BREAKPOINT(代码= 1,子代码= 0x1007efc14)"在我的AppDelegate中。我该如何解决这个问题?

3 个答案:

答案 0 :(得分:0)

place.addingPercentEncoding(withAllowedCharacters:.urlQueryAllowed) 或制作可链接的网址(删除空格或其他)

答案 1 :(得分:0)

我找到了另一种解决方案,只需删除像这样的空格

for place in placesArray {
    let range = (text as NSString).range(of: place)
    attributedText.addAttribute(NSFontAttributeName, value: UIFont(name:"Helvetica-Bold", size:16.0)!, range: range)

--> let newPlace = place.replacingOccurrences(of: " ", with: "")

    attributedText.addAttribute(NSLinkAttributeName, value: newPlace, range: range)
}

希望它有所帮助。

答案 2 :(得分:0)

我最终使用addingPercentEncoding

for place in placesArray {

    let value = place.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
    let range = (text as NSString).range(of: place)

    attributedText?.addAttribute(NSFontAttributeName, value: UIFont(name:"Helvetica-Bold", size:16.0)!, range: range)
    attributedText?.addAttribute(NSLinkAttributeName, value: value!, range: range)

}