How to set color of templated image in NSTextAttachment

后端 未结 7 1090
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-29 20:30

How can I set the color of a templated image that is an attachment on an attributed string?

Background:

I\'ve got a UILabel and I\'m setting its attributedTe

7条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-29 20:47

    I use this NSMutableAttributedString extension for Swift.

    extension NSMutableAttributedString {
        func addImageAttachment(image: UIImage, font: UIFont, textColor: UIColor, size: CGSize? = nil) {
            let textAttributes: [NSAttributedString.Key: Any] = [
                .strokeColor: textColor,
                .foregroundColor: textColor,
                .font: font
            ]
    
            self.append(
                NSAttributedString.init(
                    //U+200C (zero-width non-joiner) is a non-printing character. It will not paste unnecessary space.
                    string: "\u{200c}",
                    attributes: textAttributes
                )
            )
    
            let attachment = NSTextAttachment()
            attachment.image = image.withRenderingMode(.alwaysTemplate)
            //Uncomment to set size of image. 
            //P.S. font.capHeight sets height of image equal to font size.
            //let imageSize = size ?? CGSize.init(width: font.capHeight, height: font.capHeight)
            //attachment.bounds = CGRect(
            //    x: 0,
            //    y: 0,
            //    width: imageSize.width,
            //    height: imageSize.height
            //)
            let attachmentString = NSMutableAttributedString(attachment: attachment)
            attachmentString.addAttributes(
                textAttributes,
                range: NSMakeRange(
                    0,
                    attachmentString.length
                )
            )
            self.append(attachmentString)
        }
    }
    

    This is how to use it.

    let attributedString = NSMutableAttributedString()
    if let image = UIImage.init(named: "image") {
        attributedString.addImageAttachment(image: image, font: .systemFont(ofSize: 14), textColor: .red)
    }
    

    You can also change addImageAttachment's parameter image: UIImage to image: UIImage? and check the nullability in extension.

提交回复
热议问题