通过UILabel文本的第一行将图像居中 [英] Center image by first line of UILabel text

查看:70
本文介绍了通过UILabel文本的第一行将图像居中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将图像居中到UILabel文本第一行的Y中心.我使用砖石来设置自动布局"约束,例如:

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);
    }];

应该很直接.我只是将UIImageView的顶部附加到我的Label的顶部.

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

但请看一下屏幕.

UIImageView(灰色点)和标签的顶部边缘相等,但是如何使UIImageView这样居中放置在文本的第一行?

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?

谢谢.

推荐答案

实际上,有一种方法可以做到!如果您使用普通的旧版AutoLayout,则可以使用以下代码段完成此操作:

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)

第一个约束将在标签第一行的Y中心显示您的图标.第二个图标将您的图标放在标签的左侧,并在它们之间创建一个10pt的空格.

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.

希望这会有所帮助!

这篇关于通过UILabel文本的第一行将图像居中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆