保持UIImageView和UILabel中心对齐

时间:2014-07-16 08:04:56

标签: ios uiimageview uilabel autolayout

我通过XIB将UIImageViewUILabel并排放置在屏幕中央,现在标签文字可以是小/大,动态,图像是恒定的。

当标签文字较小时,图像和标签看起来居中对齐,但是当标签文字很大时,图像保持居中对齐,但现在标签尾部几乎触及屏幕。

这是图片:

enter image description here

希望你有这个,我怎么能让这两个(图像和标签)中心始终对齐。

2 个答案:

答案 0 :(得分:2)

- (void)alignImageView:(UIImageView *)imageView andLabel:(UILabel *)label inSuperView:(UIView *)superView {
  [label sizeToFit]; // Resize the label to have a frame that perfectly fit the content
  /* We first set the X origin of the imageView,
   * To center anything on the X axis, the common way is to say that x is "(superview.width - subview.width) / 2"
   * Here subview width is imageView.width + label.width
   */
  [imageView setFrame:CGRectMake((superView.frame.size.width - imageView.frame.size.width - label.frame.size.width) / 2, imageView.frame.origin.y, imageView.frame.size.width, imageView.frame.size.height)];
   /* According to the previous calculation, we just have to say that the x origin for the label is just at the end of the imageView (origin + size)
    */
  [label setFrame:CGRectMake(imageView.frame.origin.x + imageView.frame.size.width, label.frame.origin.y, label.frame.size.width, label.frame.size.height)];
}

这样的事情应该有用。

答案 1 :(得分:0)

如果您使用的是XIB,则应使用自动布局来设置约束。按住Ctrl键,同时单击并从一个视图拖动到另一个视图,然后选择所需的选项。

autolayoutbox