Center NSTextAttachment image next to single line UILabel

后端 未结 10 1092
太阳男子
太阳男子 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:28

    If you have a very large ascendent and want to center the image (center of the cap height) like me try this

    let attachment: NSTextAttachment = NSTextAttachment()
    attachment.image = image
    if let image = attachment.image{
        let y = -(font.ascender-font.capHeight/2-image.size.height/2)
        attachment.bounds = CGRect(x: 0, y: y, width: image.size.width, height: image.size.height).integral
    }
    

    The y calculation is as the picture below

    Note that the y value is 0 because we want the image to shift down from the origin

    If you want it to be in the middle of the whole label.Use this y value:

    let y = -((font.ascender-font.descender)/2-image.size.height/2)
    

提交回复
热议问题