objective-c - 将 UIImageView 随机放置在 UIView 上并且不重叠

标签 objective-c ios uiview uiimageview

我正在做的是将 UIImageViews 随机放置在 View 上,我让该部分工作,我所做的就是这样:

return (int)0 + arc4random() % (self.view.bounds.frame.size.height-0+1);

还有宽度。

我遇到的是一些UIImageViews相互重叠。我知道我可以使用 CGRectIntersectsRect ,但是如何循环它直到所有 UIImageViews 不相互重叠?

最佳答案

以下是如何修改当前方法来放置 ImageView 的示例,如我之前的评论中所述:

// make sure this array is a member object, else pass it to the makeFrame method below.
NSArray *imageviews = [[NSArray alloc] initWithObjects: view1, view2, view3, nil]; // make sure they have tags! set the .tag property of each imageview in the array.
UIView *mainView = nil; // this won't really be nil - this is the view you are adding your imageviews to.

for (int i = 0; i < [imageviews count]; i++)
{
    UIImageView *imageview = [imageviews objectAtIndex: i];
    CGRect newFrame = [self makeFrameForView: imageview];

    while (newFrame.origin.x == 0 && newFrame.origin.y == 0)
    {
        // then the method returned CGRectZero. create it again until we get a good frame.
        newFrame = [self makeFrameForView: imageview];
    }

    [imageview setFrame: newFrame];
}


-(CGRect)makeFrameForView: (UIImageView*)theImageView
{
    CGRect newFrame = nil; // create your new frame here using arc4random etc and the parameters you prefer.

    for (int i = 0; i < [imageviews count]; i++)
    {
        UIImageView *imageview = [imageviews objectAtIndex: i];

        // first, ensure you aren't checking the same view against itself!
        if (theImageView.tag != imageview.tag)
        {
            BOOL intersectsRect = CGRectIntersectsRect(imageview.frame, newFrame);

            if (intersectsRect)
                return CGRectZero; // throw an "error" rect we can act upon.

        }
    }

    return newFrame;
}

关于objective-c - 将 UIImageView 随机放置在 UIView 上并且不重叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14073668/

相关文章:

ios - 如何用字符串数组中的 %20 填充空字符串 ios

objective-c - 单击取消按钮时出现消息框

ios - 使用 Storyboard和导航 Controller 检测 MPMoviePlayerController 上的点击

iphone - iOS block - 使用未声明的标识符 self

iphone - 适用于 iPhone 的类似 Web 的选项卡

iOS - 设置 UIView 阴影时偏移和插入之间的区别?

ios - 通过电子邮件从我的应用程序发送多个递增的 csvs

iphone - iPhone 应用程序中的 Gmail 身份验证

php - 将数据从 PHP 脚本发送到 iOS

ios - 没有混合层的圆形 UIView(带 cornerRadius)