Hi I am beginner to iOS and I have a question.
I want to re arrange multiple buttons when changing orientations so i have this code to create them :
NSArray *buttonImages = [[NSArray alloc] initWithObjects:@"button_1.png",@"button_2.png",
@"button_3.png", @"button_4.png", nil];
int xcord = 0;
//int ycord = 0;
UIInterfaceOrientation destOrientation = self.interfaceOrientation;
if (destOrientation == UIInterfaceOrientationPortrait || destOrientation == UIInterfaceOrientationPortraitUpsideDown) {
screenWidth = 768;
} else {
screenWidth = 1024;
}
int buttonWidth = 57;
int buttonHeight = 86;
int screenHorizontalDivisions = screenWidth / 5;
for (int i=0; i<4; i++) {
int buttonStartingOffset = screenHorizontalDivisions - buttonWidth / 2;
btn = [[DashButton alloc] initWithFrame:CGRectMake(buttonStartingOffset + xcord, 40, buttonWidth,buttonHeight) andImage:[buttonImages objectAtIndex:i] andTitle:@"Test"];
btn.tag = i+1;
[springboardScrollView addSubview:btn];
//[btn release];
xcord = xcord + screenHorizontalDivisions;
}
and the code to re arrange them is:
- (void)animate: (id)开发者_如何学编程sender {
UIButton *button = (UIButton *)sender;
UIInterfaceOrientation destOrientation = self.interfaceOrientation;
if (destOrientation == UIInterfaceOrientationPortrait || destOrientation == UIInterfaceOrientationPortraitUpsideDown) {
screenWidth = 768;
} else {
screenWidth = 1024;
}
int xcord = 0;
int buttonWidth = 57;
int buttonHeight = 86;
int screenHorizontalDivisions = screenWidth / 5; //find the divisions
int buttonStartingOffset = screenHorizontalDivisions - buttonWidth / 2; //center the button
NSLog (@"%i", button.tag);
switch (button.tag) {
case 1:
button.frame = CGRectMake(buttonStartingOffset, 40, buttonWidth,buttonHeight);
break;
case 2:
button.frame = CGRectMake(buttonStartingOffset + screenHorizontalDivisions, 40, buttonWidth,buttonHeight);
break;
case 3:
button.frame = CGRectMake(buttonStartingOffset + screenHorizontalDivisions * 2, 40, buttonWidth,buttonHeight);
break;
case 4:
button.frame = CGRectMake(buttonStartingOffset + screenHorizontalDivisions * 3, 40, buttonWidth,buttonHeight);
break;
}
then I am calling it when orientation changes:
- (void)willAnimateSecondHalfOfRotationFromInterfaceOrientation: (UIInterfaceOrientation) fromInterfaceOrientation duration: (NSTimeInterval) duration {
[self animate:btn];
How can I refer to each button one by one? The code in animate: always return button.tag=4.
Please assist!!
Thanks Bill.
You need to get the array of UIButtons with the following code:
NSArray* buttons = [springboardScrollView subviews]
This will return all the subviews in the scrollView. If you have UiButtons only that will be all buttons in the scroll view. If you have other types of views in scroll view then you need to iterate through array and check if the object is UiButton, which is explained on the following link . Then you can change the frame, image, position....
精彩评论