通过UILabel文本的第一行将图像居中

Evg*_*ban 5 objective-c ios autolayout

我想将图像居中到UILabel文本第一行的Y中心。我使用砖石来设置“自动布局”约束,如下所示:

 [_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);
    }];
Run Code Online (Sandbox Code Playgroud)

它应该非常简单。我只是将UIImageView的顶部附加到我的Label的顶部。

但是看看屏幕。

在此处输入图片说明

UIImageView的顶部边缘(灰色点)和label相等,但是如何使UIImageView这样居中于文本的第一行呢?

在此处输入图片说明

谢谢。

bla*_*acx 9

其实有一种方法可以做到这一点!如果您使用普通的旧 AutoLayout,则可以使用以下代码段来完成:

// 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)
Run Code Online (Sandbox Code Playgroud)

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

希望这可以帮助!


Evg*_*ban 0

我通过两个步骤实现了以下目标:

1)计算特定字体文本标签行的预期高度:

+(CGSize)getSimpleSizeBasedOnFont:(CGFloat)font{

    UILabel *lbl = [UILabel new];
    lbl.text = @"Simple text";
    lbl.font = [UIFont systemFontOfSize:font];

    return [lbl.text sizeWithFont:lbl.font
                                constrainedToSize:lbl.frame.size
                                    lineBreakMode:NSLineBreakByWordWrapping];
}
Run Code Online (Sandbox Code Playgroud)
  1. 然后我向 UIImage View 的中心 Y 添加约束,偏移量等于该高度的 50%:

CGFloat lblOffs = [助手 getSimpleSizeBasedOnFont:14].height; [_haveReadIndicatorImgView mas_makeConstraints:^(MASConstraintMaker *make) { make.centerY.equalTo(_topTxtlbl.mas_top).offset(lblOffs/2); make.left.equalTo(self.contentView).offset(SMALL_OFFSET); make.height.width.equalTo(@(8)); }];