swift

时间:2017-05-03 13:41:41

标签: nsattributedstring

我有一个mutableAttributedString,其中几个字符串是linkAttributed,我想找到所有链接属性字符串的范围。如何在swift3中做到这一点?

当用户在textview中键入@时,显示少数名称的列表。如果用户选择任何行,则调用以下方法。

func didSelectMemberId(_ model: BaseModel) {

    var  fullName = ""
    if model.entityType == ReceiverType.Active.rawValue{
        fullName = model.name
    }else{
        fullName = AtMention + model.name + " " + model.name2
    }
    let attributedString = NSMutableAttributedString(string:fullName, attributes:[NSFontAttributeName:(appNeedsAutoResize ? (UIUtils.getFontForApproprieteField(.headlineWithoutBold).font) : UIFont.systemFont(ofSize: 14))])

    attributedString.addAttribute(NSLinkAttributeName, value: "connectmention://\(model.entityId.stringValue())", range: NSRange(location: 0, length: fullName.length))

    attributedString.append(NSAttributedString(string: emptySpaceStringByUC, attributes:[NSFontAttributeName:(appNeedsAutoResize ? (UIUtils.getFontForApproprieteField(.headlineWithoutBold).font) : UIFont.systemFont(ofSize: 14))]))


    self.composeBar.textView.textStorage.insert(attributedString, at:self.composeBar.textView.selectedRange.location)

 }
    self.composeBar.textView.selectedRange = NSMakeRange(self.composeBar.textView.selectedRange.location+fullName.length, 0 )

要获得链接支持,我使用以下方法

      func getlinkActionRange(attributeString: NSAttributedString) -> [MentionStruct] {
    var arrMentions = [MentionStruct]()
    _ =  attributeString.enumerateAttribute(NSLinkAttributeName, in: NSRange.init(location: 0, length: attributeString.length), options: [], using: { (value, range, stop) in
        if let url = value {
            let occurrence = (attributeString.string as NSString).substring(with:range)
            arrMentions.append(MentionStruct(link: url as! String, text: occurrence, range: range))
        }
    })
    return arrMentions
}

如果用户在插入该名称后键入任何内容,则该类型字符串也会出现。

0 个答案:

没有答案