保持UIImageView和UILabel居中对齐

我有一个UIImageViewUILabel通过XIB并排放置在屏幕的中心,现在标签文本可以是小/大,它的动态图像是恒定的。

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

这是图像:

在这里输入图像描述

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


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

像这样的东西应该工作。


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

autolayoutbox

链接地址: http://www.djcxy.com/p/28295.html

上一篇: Keep UIImageView and UILabel center aligned

下一篇: Center vertically in UILabel with autoshrink