如何设置视图框架宽度? (为什么我不能直接设置?)

时间:2012-05-22 08:46:42

标签: iphone objective-c ios uiview positioning

我想重置一个UIView的帧大小,所以我写道:

view.frame.size.width = x;

但它不起作用,谁能告诉我为什么?

4 个答案:

答案 0 :(得分:16)

您无法直接设置宽度,请执行此操作

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

答案 1 :(得分:7)

当您致电view.frame时,您会获得一份frame rect属性的副本,因此设置frame.size.width时会更改副本的宽度而不是视图的帧大小

答案 2 :(得分:3)

这是为什么的一次传球。您的代码转换为

[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

另一种思考方式是,那里有一个看不见的变量,你无法访问:

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

答案 3 :(得分:1)

-(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];
}