iPhone UIView - Resize Frame to Fit Subviews

前端 未结 11 1533
时光取名叫无心
时光取名叫无心 2020-12-04 17:51

Shouldn\'t there be a way to resize the frame of a UIView after you\'ve added subviews so that the frame is the size needed to enclose all the subviews? If your subviews are

11条回答
  •  执笔经年
    2020-12-04 18:34

    You could also add the following code to calculate subviews position.

    [myView resizeToFitSubviews]
    

    UIViewUtils.h

    #import 
    
    @interface UIView (UIView_Expanded)
    
    -(void)resizeToFitSubviews;
    
    @end
    

    UIViewUtils.m

    #import "UIViewUtils.h"
    
    @implementation UIView (UIView_Expanded)
    
    -(void)resizeToFitSubviews
    {
        float w = 0;
        float h = 0;
    
        for (UIView *v in [self subviews]) {
            float fw = v.frame.origin.x + v.frame.size.width;
            float fh = v.frame.origin.y + v.frame.size.height;
            w = MAX(fw, w);
            h = MAX(fh, h);
        }
        [self setFrame:CGRectMake(self.frame.origin.x, self.frame.origin.y, w, h)];
    }
    
    @end
    

提交回复
热议问题