我正在尝试创建一个属性字符串,在该属性字符串的末尾附加一个链接:

func addMoreAndLessFunctionality (textView:UITextView){
        if textView.text.characters.count >= 120
        {
            let lengthOfString = 255
            var abc : String =  (somelongStringInitiallyAvailable as NSString).substringWithRange(NSRange(location: 0, length: lengthOfString))
            abc += " ...More"
            textView.text = abc
            let attribs = [NSForegroundColorAttributeName: StyleKit.appDescriptionColor, NSFontAttributeName: StyleKit.appDescriptionFont]
            let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: abc, attributes: attribs)


            attributedString.addAttribute(NSLinkAttributeName, value: " ...More", range: NSRange(location:255, length: 8))

          textView.attributedText = attributedString
            textView.textContainer.maximumNumberOfLines = 3;

        }
}

我要在这里实现的是,如果文本视图中的文本中的字符超过255个,则应该在文本视图中显示“...更多”链接,该链接是可点击的,在点击时我已经能够获得名为“shouldInteractWithUrl”的委托,其中我增加了文本视图中的行数,还将链接的文本更改为“...少”。点击Less,我再次调用此相同方法,以便可以再次截断。 :
    func textView(textView: UITextView, shouldInteractWithURL URL: NSURL, inRange characterRange: NSRange) -> Bool
{
    print("textview should interact with URl")

    let textTapped = textView.text[textView.text.startIndex.advancedBy(characterRange.location)..<textView.text.endIndex]

    if textTapped == " ...More"{

        var abc : String =  (self.contentDetailItemManaged?.whatsnewDesc)!
        abc += " ...Less"
        textView.textContainer.maximumNumberOfLines = 0
        let attribs = [NSForegroundColorAttributeName: StyleKit.appDescriptionColor, NSFontAttributeName: StyleKit.appDescriptionFont]
        let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: abc, attributes: attribs)
        attributedString.addAttribute(NSLinkAttributeName, value: " ...Less", range: NSRange(location:abc.characters.count-8 , length: 8))

        textView.attributedText = attributedString


    }
    else if textTapped == " ...Less"{

        textView.attributedText = nil
        textView.text = somelongStringInitiallyAvailable
        self.addMoreAndLessFunctionality(textView)
    }

    return true
}

现在的问题是,第一次调用第一种方法时(在我设置了textview的文本后调用),它可以正常工作,但是在单击“... More”后,textview会正常展开,“...更多”更改为“...减少”。当点击“...少”时,它崩溃并发生异常:
[NSConcreteTextStorage attribute:atIndex:effectiveRange:]: Range or index out of bounds'

任何帮助将不胜感激。 (字符串“... More”开头也有一个空格,所以总共8个字符,我在键入上面的代码时可能错过了这个空格)

谢谢 :)

最佳答案

return false中的func textView(textView: UITextView, shouldInteractWithURL URL: NSURL, inRange characterRange: NSRange) -> Bool

10-07 19:49
查看更多