UIScrollview calling superviews layoutSubviews when scrolling?

后端 未结 3 1807
走了就别回头了
走了就别回头了 2021-02-13 21:31

I added a UITableView as a subview to a custom UIView class I\'m working on. However I noticed that whenever I scroll the table it calls my classes layoutSubviews. I\'m pretty

3条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-13 22:09

    UITableView at least does appear to layout its superview. This behavior can be problematic when you have a layoutSubviews method that might be expensive (e.g. if you call some JavaScript).

    The quick fix is add an intermediary subview that prevents the scroll view from laying out your superview. Instead, it will layout the intermediate subview.

    This could be somewhat imperfect but it should work for most cases:

    Assume UIView * intermediateView is defined as an instance variable:

    -(id) initWithFrame:(CGRect)frame
    {
        self = [super initWithFrame: frame];
        if (self)
        {
            UIScrollView * theScrollView; // = your scroll view or table view
            intermediateView = [[[UIView alloc] initWithFrame:CGRectZero] autorelease];
            // Ensures your intermediate view will resize its subviews.
            intermediateView.autoresizesSubviews = YES;
    
            // Ensure when the intermediate view is resized that the scroll view
            // is given identical height and width.
            theScrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth |
                                             UIViewAutoresizingFlexibleHeight;
            [intermediateView addSubview: theScrollView];
    
            // Ensure the frame of the scroll view is exactly the bounds of your
            // intermediate view.
            theScrollView.frame = bottomContainerView.bounds;
            [self addSubview: intermediateView];
        }
        return self;
    }
    
    -(void) layoutSubviews
    {
        intermediateView.frame = CGRectMake(0, 50, 42, 42); // replace with your logic
    }
    

提交回复
热议问题