Ios 保持UIImageView和UILabel中心对齐
我有一个Ios 保持UIImageView和UILabel中心对齐,ios,uiimageview,uilabel,autolayout,Ios,Uiimageview,Uilabel,Autolayout,我有一个UIImageView和一个UILabel通过XIB并排放置在屏幕中央,现在标签文本可以是小/大的,其动态图像是恒定的 当标签文本较小时,图像和标签看起来居中对齐,但当标签文本较大时,图像保持居中对齐,但现在标签尾部几乎接触屏幕 图为: 希望你有这个,我怎样才能使这两个(图像和标签)的中心始终对齐 - (void)alignImageView:(UIImageView *)imageView andLabel:(UILabel *)label inSuperView:(UIView *
UIImageView
和一个UILabel
通过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键,同时单击并从一个视图拖动到另一个视图,然后选择所需的选项
我不是自动布局方面的专家,但这不是一种从一个视图到另一个视图的“ctrl+单击并拖动”并设置中心对齐约束的方式吗?您好,这很有效,但不是一种更简单的方式,如果不是,您能解释一下您是如何找到这个解决方案的吗?Bcoz,这种情况在大多数情况下我们都需要。@Ranjit添加注释,希望它更容易理解:)!非常感谢,我收到了it@KIDdAe为了使其更通用,您可以将self.view替换为imageView.superview。然后,即使superview不是UIViewController根视图,它也可以工作。唯一重要的是imageView和label是同一视图的子视图。@VictorMaiaAldecôa事实上,我添加了与superview相对应的第三个参数。使用
imageView.superView
意味着imageView已经是superView的子视图。然后我宁愿写一些完全通用的东西:)!我没有使用自动布局