Undo
Undo

Reputation: 25697

iOS Programming Center Group of UIViews

I am wondering how/if I could do this: center a group of UIView's in a superview. The end result would be a 'group' of views that are visibly centered in their superview.

Upvotes: 1

Views: 203

Answers (1)

Khaled Barazi
Khaled Barazi

Reputation: 8741

Well, it is a 2 step process; first add the UIViews to an array and then do a fast enumeration to center them as a "group"

//step 1: create the objects
self.label1= [[UILabel alloc]init];
self.label1.font=[UIFont systemFontOfSize:30.0];
self.label1.text=@"1";

self.label2= [[UILabel alloc]init];
self.label2.font=[UIFont systemFontOfSize:30.0];
self.label2.text=@"2";

self.label3= [[UILabel alloc]init];
self.label3.font=[UIFont systemFontOfSize:30.0];
self.label3.text=@"3";


//step2: create the array and add the objects to the array
self.arrayOfViews=[[NSMutableArray alloc]initWithCapacity:4];
[self.arrayOfViews addObject:self.label1];
[self.arrayOfViews addObject:self.label2];
[self.arrayOfViews addObject:self.label3];



//step3: use fast enumeration to be able to control them as "group"
for(UIView* currentViewObject in self.arrayOfViews)
{
    currentViewObject.alpha=0.3;
    currentViewObject.frame=CGRectMake(self.view.bounds.size.width/2-sizeOfObject/2,self.view.bounds.size.height/2-sizeOfObject/2,sizeOfObject,sizeOfObject);
    [self.view addSubview:currentViewObject];
}

Step 1 and the alpha setting is just for testing purpose here.

Hope this helps.

Upvotes: 1

Related Questions