NSAttributedString获取部分图像和字符串

时间:2016-09-05 20:47:15

标签: swift uitextview

我有一个NSAttributedString混合了StringNSTextAttachment,其中有图像。我如何提取[AnyObject]部分的数组?

2 个答案:

答案 0 :(得分:2)

我想通了你可以迭代所有attributedString并读取对象是否有NSTextAttachmentAttributeName属性。如果没有,假设它是一个字符串。

extension UITextView {
    func getParts() -> [AnyObject] {
            var parts = [AnyObject]()

            let attributedString = self.attributedText
            let range = NSMakeRange(0, attributedString.length)
            attributedString.enumerateAttributesInRange(range, options: NSAttributedStringEnumerationOptions(rawValue: 0)) { (object, range, stop) in

                if object.keys.contains(NSAttachmentAttributeName) {
                    if let attachment = object[NSAttachmentAttributeName] as? NSTextAttachment {
                        if let image = attachment.image {
                            parts.append(image)
                        }else if let image = attachment.imageForBounds(attachment.bounds, textContainer: nil, characterIndex: range.location) {
                            parts.append(image)
                        }
                    }
                }else {
                    let stringValue : String = attributedString.attributedSubstringFromRange(range).string
                    if !stringValue.isEmptyOrWhitespace() {
                        parts.append(stringValue)
                    }
                }
            }


            return parts
        }
}

答案 1 :(得分:1)

这在Swift 4中对我有用:

extension UITextView {
    func getParts() -> [AnyObject] {
        var parts = [AnyObject]()

        let attributedString = self.attributedText
        let range = NSMakeRange(0, attributedString.length)
        attributedString.enumerateAttributes(in: range, options: NSAttributedString.EnumerationOptions(rawValue: 0)) { (object, range, stop) in
            if object.keys.contains(NSAttributedStringKey.attachment) {
                if let attachment = object[NSAttributedStringKey.attachment] as? NSTextAttachment {
                    if let image = attachment.image {
                        parts.append(image)
                    } else if let image = attachment.image(forBounds: attachment.bounds, textContainer: nil, characterIndex: range.location) {
                        parts.append(image)
                    }
                }
            } else {
                let stringValue : String = attributedString.attributedSubstring(from: range).string
                if (!stringValue.trimmingCharacters(in: .whitespaces).isEmpty) {
                    parts.append(stringValue as AnyObject)
                }
            }
        }
        return parts
    }