【问题标题】:How to set a views frame width? (Why can't I set it directly?)如何设置视图框架宽度? (为什么不能直接设置?)
【发布时间】:2012-05-28 17:50:36
【问题描述】:

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

view.frame.size.width = x;

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

【问题讨论】:

    标签: iphone objective-c ios uiview positioning


    【解决方案1】:

    你不能直接设置宽度,这样做

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

    【讨论】:

    • 是的,但是我想知道这两种代码风格有什么区别,如果我的代码通过会导致什么。
    • 因为 view 的 frame 属性返回一个新的 frame 而不是拥有 view 的。并且你设置了新获取的框架的宽度,这不会影响
    【解决方案2】:

    当您调用 view.frame 时,您会获得 frame rect 属性的副本,因此使用 frame.size.width 设置它会更改副本的宽度,而不是视图的框架大小

    【讨论】:

      【解决方案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;
      

      【讨论】:

        【解决方案4】:
        -(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];
        }
        

        【讨论】:

          猜你喜欢
          • 2015-03-10
          • 1970-01-01
          • 1970-01-01
          • 2011-10-28
          • 1970-01-01
          • 2012-01-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多