Search code examples
objective-cipaduibuttonautoresizingmask

How to handle autoresizing on UIButton elements which has been created dynamically


I create some buttons dynamically on my view and i decide their frames according to some of my JSON respone parameters. But i want to autoresize them when the device(dsimulator) rotates. I can easily do this on interface builder but can't do anything on dynamic ones. Can someone help? EDIT

Here is a snipped of my code

if (button.tag==1) {
    button.frame = CGRectMake(30.0f, yPosition, 200.0f, buttonHeight);
}
if (button.tag==2) {
    button.frame = CGRectMake(280.0f, yPosition, 200.0f, buttonHeight);
}
if (button.tag==3) {
    button.frame = CGRectMake(530.0f, yPosition, 200.0f, buttonHeight);
}

There is no problem when using Portraid mode but when it rotates to Landscape a big empty area stays on the right side of the screen. How can i fix this?(I mean, when i rotate, i want the buttons got to the center of the scren's width)

EDIT: I played with autoresizing on Size Inspector(Xcode 4.3) with my xib file and it works great, but whatever i did i couldn't resize the dynamically created buttons after rotation. I tried almost all of AutoresizingMask enums of UIView but nothing changes. Can someone please help


Solution

  • The attributes you've set up in your interface builder file are the UIViewAutoresizing attributes.

    Take a look at this documentation from Apple on the UIView class (which your button is a subclass of); look for the UIViewAutoresizing attribute. That's the one you'll want.

    Update: Here's a snippet of code for an MKMapView that uses this ability:

    mainMapView = [[MKMapView alloc] initWithFrame:CGRectMake(20, 239, 280, 122)];
    [mainMapView setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin];
    

    With UIViewAutoresizingFlexibleTopMargin, the map view moves down when the user answers the phone --- it fixes the map's position relative to the top of the screen.

    Dig around in the documentation and you'll find the autoresizing mask that works best for your situation.