Kaibin
Kaibin

Reputation: 474

How to set a views frame width? (Why can't I set it directly?)

I want to reset a UIView's frame size so I wrote:

view.frame.size.width = x;

but it doesn't work, can anyone tell me why?

Upvotes: 9

Views: 11729

Answers (4)

Saad
Saad

Reputation: 8947

you can't set width directly, do this

CGRect frm = view.frame;
frm.size.width = x;
view.frame = frm;

Upvotes: 18

Gank
Gank

Reputation: 4667

-(void)changeWidth:(UIView*)view wid:(int)newWid{
    CGRect rc=view.frame;
    view.frame=CGRectMake(rc.origin.x, rc.origin.y, newWid, rc.size.height);
}

- (void) adjustViewtForNewOrientation: (UIInterfaceOrientation) orientation {
    //if (UIInterfaceOrientationIsLandscape(orientation)) {
    loadMoreView.frame=CGRectMake(0, 0, WIDTH, 50);
    headerView.frame=CGRectMake(0, [MLTool getPaddingHeight:self], WIDTH, HEI_SEGMENT);
    [self changeWidth:webview wid:WIDTH];
    [self changeWidth:tableView wid:WIDTH];
    [self changeWidth:  segmentedControl  wid:WIDTH-SEG_LEFT*2];
}

Upvotes: 1

Clay Bridges
Clay Bridges

Reputation: 11860

Here's one pass at why. Your code translates into

[view frame] // <- This hands you a CGRect struct, which is not an object.
             //    At this point, view is out of the game.
.size        // <- On the struct you were handed
.width       //             "
= x;         // <- the struct you were handed changed, but view was untouched

One other way of thinking of it is that there is an invisible variable there, that you can't access:

 CGRect _ = [view frame]; // hands you a struct
 _.size.width = x;

Upvotes: 3

giorashc
giorashc

Reputation: 13713

When you call view.frame you get a copy of the frame rect property so setting it is with frame.size.width changes the width of the copy and not the view's frame size

Upvotes: 7

Related Questions