【问题标题】:Dynamically Add and Center UIImages in UIView在 UIView 中动态添加和居中 UIImages
【发布时间】:2015-03-24 08:07:40
【问题描述】:

我正在努力思考这个有趣的“问题”。

我有一个 UIView (288x36),最多可容纳 8 个 UIImage (36x36)。 UIView 中可以放置任何数字(最多 8 个)。 我希望这些图像的“集合”在 UIView 中居中。

如果只有 1 张图片,那么它的中心将在 UIView 的中心。如果为 2,则图像的最大宽度将在 UIView 的中心,并且第二个图像的起点也将在中心等。

以前有没有人处理过这个问题?任何代码示例。

我不是很先进,但正在努力学习。

【问题讨论】:

    标签: ios xcode uiview


    【解决方案1】:

    假设您的UIView 被称为view 并且您的图像数组是imageArray

    float remainingSpace = view.bounds.size.width - imageArray.count*36; //This is the space to remaining
    float spaceOnLeft = remainingSpace/2.0; //Just the space to the left of the images
    for (UIImage *image in images) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(spaceOnLeft, 0, 36, 36)];
        imageView.image = image;
        [view addSubview:imageView];
        spaceOnLeft += 36.0; // so the next image is spaced 36 points to the right
    }
    

    【讨论】:

    • 如果您已经创建了 imageViews(即使它们可点击),请将 for 循环更改为从 imageView 数组循环遍历 imageViews,并将 for 循环中的前 2 行替换为“[imageView setFrame:CGRectMake (spaceOnLeft, 0, 36, 36)];"
    猜你喜欢
    • 2013-02-28
    • 1970-01-01
    • 1970-01-01
    • 2015-06-14
    • 2012-02-09
    • 1970-01-01
    • 2014-05-02
    • 2015-05-07
    • 1970-01-01
    相关资源
    最近更新 更多