繁体   English   中英

iOS自动布局-以编程方式在子视图的一条水平线上显示多张图像

[英]IOS Autolayout- Multiple images in one horizontal line of subview programmatically

我创建了一个tableview标头,并为其添加了一个子视图。 我试图在此ui子视图的一行中将多个头像图像(固定的宽度和高度)居中。

最大图像数=最大(预定义)。 我要容纳的图像数量为n。

当最大图像数为5时,

n = 1:

[......................图像1 ................................ ..]

n = 2:

[........图像1 ......图像2 ......]

n = 3

[.........图像1 .....图像2 ....图像3 ......]

n = 4

[...图像1 ....图像2 ....图像3 ...图像4 ...]

n = 5

[.imag 1 .... imag2 .... imag3 .... imag4 .... imag5。]

也就是说,放置位置应以相等的间距居中。

如何以编程方式实现这一目标?

我可以通过故事板来实现此目的,方法是将最大图像连续放置,并保持相等的前导和尾随空格,并且当n = 1时,我将隐藏1,2,4和5

而当n = 2时,我将隐藏1,2,5

如果您可以将iOS 9及更高版本的部署目标作为目标,请使用UIStackView 它旨在处理这种情况。

如果您还不能执行此操作,则以下算法将起作用。 它不使用约束。

CGFloat tableWidth = ...; // This may change if you allow rotation.
CGFloat spacer = ...; // Amount of space between images goes here.
CGFloat imageWidth = images.count > 0 ? [[images[0] size] width] : 0.0;
CGFloat imageHeight = images.count > 0 ? [[images[0] size] height] : 0.0;
CGFloat totalWidth = images.count * imageWidth + (images.count - 1) * spacer;
CGFloat leftEdge = (tableWidth / 2.0) - (totalWidth / 2.0);

for (int i = 0; i < images.count; i++) {
    UIImageView *iv = ...; // Create and configure with image[i].

    CGRect frame = CGMakeRect(0, 0, imageWidth, imageHeight);
    frame.origin.x = leftEdge + (i * imageWidth + i * spacer);
    iv.frame = frame;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM