Center NSTextAttachment image next to single line UILabel

后端 未结 10 1124
太阳男子
太阳男子 2020-11-30 16:51

I\'d like to append an NSTextAttachment image to my attributed string and have it centered vertically.

I\'ve used the following code to create my string

10条回答
  •  既然无缘
    2020-11-30 17:14

    In my case calling sizeToFit() helped. In swift 5.1

    Inside your custom label:

    func updateUI(text: String?) {
        guard let text = text else {
            attributedText = nil
            return
        }
    
        let attributedString = NSMutableAttributedString(string:"")
    
        let textAttachment = NSTextAttachment ()
        textAttachment.image = image
    
        let sizeSide: CGFloat = 8
        let iconsSize = CGRect(x: CGFloat(0),
                               y: (font.capHeight - sizeSide) / 2,
                               width: sizeSide,
                               height: sizeSide)
        textAttachment.bounds = iconsSize
    
        attributedString.append(NSAttributedString(attachment: textAttachment))
        attributedString.append(NSMutableAttributedString(string: text))
        attributedText = attributedString
    
        sizeToFit()
    }
    

提交回复
热议问题