滚动时UIScrollview调用superviews layoutSubviews?

时间:2010-05-12 02:59:53

标签: iphone uitableview uiview uiscrollview

我将UITableView作为子视图添加到我正在处理的自定义UIView类中。但是我注意到每当我滚动表时它都会调用我的类layoutSubviews。我很确定UIScrollview表是继承的,实际上是在做这个,但想知道是否有办法禁用这个功能,如果不是为什么会发生?我不明白为什么当你滚动一个scrollview时,它需要超级视图来布局它的子视图。

代码:

@implementation CustomView
- (id)initWithFrame:(CGRect)frame {
    if ((self = [super initWithFrame:frame])) {
        self.clipsToBounds = YES;

        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0.0, 15.0, 436.0, 132.0) style:UITableViewStylePlain];
        tableView.dataSource = self;
        tableView.delegate = self;
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        tableView.backgroundColor = [UIColor clearColor];
        tableView.showsVerticalScrollIndicator = NO;
        tableView.contentInset = UIEdgeInsetsMake(kRowHeight, 0.0, kRowHeight, 0.0);
        tableView.tag = componentIndex;

        [self addSubview:tableView];
        [tableView release];
    }
    return self;
}
- (void)layoutSubviews {
    // This is called everytime I scroll the tableview
}

@end

3 个答案:

答案 0 :(得分:2)

是的,UIScrollView会在滚动时调用layoutsubviews。我可以发誓,这在某处的文档中有说明,但我猜不是。

无论如何,对此的普遍看法是UIScrollView应该布局其内容,以便不应该布置当前看不到的视图。当用户在滚动视图中滚动时,它应根据需要添加和删除子视图。我猜这是TableViews用来排队隐藏的表格单元格。

是否有任何理由说明如何调用layoutsubviews?

答案 1 :(得分:1)

UITableView至少看起来布局了它的超级视图。当你有一个可能很昂贵的layoutSubviews方法时,这种行为可能会有问题(例如,如果你调用一些JavaScript)。

快速修复是添加一个中间子视图,阻止滚动视图布局您的超级视图。相反,它将布局中间子视图。

这可能有点不完美,但它适用于大多数情况:

假设UIView * intermediateView被定义为实例变量:

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

答案 2 :(得分:0)

不确定我是否正确理解了您的问题但是当您滚动一个tableview时,它会删除内存中未显示的单元格,并在它们滚动回到可见性时再次加载它们(单元格按需分配,只有可见的单元格),做你似乎在描述的事情。

相关问题