我想将图像居中到我的 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);
}];
它应该非常简单。我只是将 UIImageView 的顶部附加到我的 Label 的顶部。
但是看看屏幕。
UIImageView(灰点)和标签的上边缘是相等的,但是如何使 UIImageView 像这样居中到文本的第一行?
谢谢。
最佳答案
其实有办法做到这一点!如果您使用普通的旧版 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)
第一个约束将在标签第一行的 Y 中心显示您的图标。第二个将您的图标放在标签的左侧,并在它们之间创建一个 10pt 的空间。
希望这对您有所帮助!
关于ios - 以 UILabel 文本的第一行居中图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44516420/