Keep UIImageView and UILabel center aligned

I have a UIImageView and a UILabel placed side by side at the center of the screen through XIB, Now the label text can be small/large, its dynamic, image is constant.

When the label text is small, image and label look center aligned, but when label text is large, image remains center aligned, but now the label tail almost touches the screen.

Here is the image:

在这里输入图像描述

Hope you have got this, how can I make this two (image and label) center aligned always.


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

像这样的东西应该工作。


If you are using XIB you should use auto layout to set your constraints. Hold the ctrl key while click and dragging from one view to the other and choose the option you want.

autolayoutbox

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

上一篇: 将单行UILabel旁边的NSTextAttachment图像居中

下一篇: 保持UIImageView和UILabel居中对齐