ios - 以 UILabel 文本的第一行居中图像

标签 ios objective-c 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);
    }];

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

但是看看屏幕。

enter image description here

UIImageView(灰点)和标签的上边缘是相等的,但是如何使 UIImageView 像这样居中到文本的第一行?

enter image description here

谢谢。

最佳答案

其实有办法做到这一点!如果您使用普通的旧版 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/

相关文章:

ios - 动画 subview AutoLayout 约束更改

objective-c - 意外的 NSAutoresizingMaskLayoutConstraint 从 Nib 添加 UIView 到自动布局 Storyboard场景

ios - 在从 UIPickerView 选择的 NSTimer 的 UILabel 中显示秒数

ios - 我如何告诉我的 ViewController 一个 View 被触摸了?

ios - 为什么我在分析中看不到崩溃日志?

ios - Xcode 7.1 更新错误

ios - Objective-C 如何只压缩视频而不压缩视频和文本叠加层?

ios - 使用 AutoLayout 的最佳实践是什么?

ios - 如何将具有相同包标识符的应用程序移动到另一个苹果开发者帐户?

iphone - 如何使用 GDataXML 解析器解析嵌套的 xml?