Reputation: 55
I'm working on an iPad application. On the main screen there are 6 buttons which was created in IB. I'd like to arrange them dynamically from code, but I can't. Already tried setting the frame/center of the objects, but they didn't move.
I have an array which holds the button outlets, and arrange them in a for loop. Is there any suggestion?
thanks!
edit:
Here's some code(not the whole, but the rest is irrelevant now), how I loop through the buttons. Button outlets already set properly. The title of the buttons changes properly, also I can hide/show the buttons, but not the position.
If I'll just try some dummy code like:
tempBtn.frame = CGRectMake(100.0, 200.0, 60.0, 40.0);
nothing changes(but I suspect all the 6 buttons should be at the same position)
// I have this array, which contains the button outlets
tAddBtnArray = [NSArray ArrayWithObjects:tAddBtn1,tAddBtn2,tAddBtn3,tAddBtn4,tAddBtn5,tAddBtn6, nil];
//I loop through the array, set button title, and trying to change the y position
for(int i=0;i<6;i++){
UIButton *tempBtn = [tAddBtnArray objectAtIndex:i];
[tempField setText:@"Set some title"];
}
Upvotes: 3
Views: 4736
Reputation: 1743
I bet I know what it is. Do you have autolayout enabled on the xib file? If so, the frame is being set, and then the constraints are being evaluated, which move the buttons back to where they were assigned.
You have two options:
I would suggest turning autolayout off, but I'm just not particularly fond of it, so it is just a preference.
Upvotes: 2
Reputation: 2992
You can add uibbutons programatically in this way:
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self
action:@selector(yourMethod:)
forControlEvents:UIControlEventTouchDown];
[button setTitle:@"Jesus Gil y Gil" forState:UIControlStateNormal];
button.frame = CGRectMake(100.0, 200.0, 60.0, 40.0);
[view addSubview:button];
Upvotes: 4