Search code examples
iosobjective-csubviewaddsubview

Issue with subviews overlapping


I'm trying to create a custom view which containes several images. I do that by adding them programmatically. The problem is that those subviews overlap each other and I can't find the way to change that. The only solution I can see is doing something like setting frames for each new image programmatically. I would be grateful if someone could tell me what is the best way to solve this issue.

for (id image in self.images) {
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
    [self.imageViews addObject:imageView];
    [self addSubview:imageView];
}

Solution

  • Without using Interface Builder your only real options are to change the frame or the center.

    imageView.frame = CGRectMake(x coord, y coord, width, height);
    

    This method lets you resize and move whereas changing the center lets you do just that, move the center of the view.

    or

    imageView.center = CGPointMake(x coord, y coord);
    

    Or as recommended add constraints.