Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center image by first line of UILabel text

I want to center image to center Y position of first line of text of my UILabel. I use masonry to set Auto Layout constraints like that:

 [_haveReadIndicatorImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.equalTo(self.contentView).offset(SMALL_OFFSET);
        make.height.width.equalTo(@(8));
    }];

    [_topTxtlbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_haveReadIndicatorImgView.mas_right).offset(TINY_OFFSET);
        make.top.equalTo(_haveReadIndicatorImgView.mas_top);
        make.right.equalTo(self.arrowImgView.mas_left).offset(-SMALL_OFFSET);
        make.bottom.equalTo(_dateTxtLbl.mas_top).offset(-SMALL_OFFSET);
    }];

It should be pretty strightforward. I simply attach top of UIImageView to top of my Label.

But take a look at screen.

enter image description here

Top edges of UIImageView (gray dot) and label are equal, but how to make UIImageView to be centered to first line of text like that?

enter image description here

Thanks.

like image 385
Evgeniy Kleban Avatar asked Jun 13 '17 08:06

Evgeniy Kleban


1 Answers

Actually there is a way of doing this! If you use plain old AutoLayout this can be done with the following snippet:

// Aligns the icon to the center of a capital letter in the first line
let offset = label.font.capHeight / 2.0

// Aligns the icon to the center of the whole line, which is different
// than above. Especially with big fonts this makes a visible difference.
let offset = (label.font.ascender + label.font.descender) / 2.0

let constraints: [NSLayoutConstraint] = [
  imageView.centerYAnchor.constraint(equalTo: label.firstBaselineAnchor, constant: -offset),
  imageView.trailingAnchor.constraint(equalTo: label.leadingAnchor, constant: -10)
]
NSLayoutConstraint.activate(constraints)

The first constraint will display your icon at the Y center of the first line of your label. The second one puts your icon left of the label and creates a 10pt space between them.

Hope this helps!

like image 73
blackjacx Avatar answered Sep 29 '22 08:09

blackjacx