4

我需要获取一个包含所有子视图的数组UIScrollView。现在我正在使用

NSArray *subviews = [myScrollView subviews];

但这似乎只返回在代码运行时可见的子视图。我需要 UIScrollView 整个范围内的所有子视图,即使是当前隐藏的子视图(如在屏幕外)。我怎么会得到那个?

本质上,我正在寻找类似于 a 的contentSize属性的东西UIScrollView,除了UIScrollView如果它足够大来显示它的所有内容,我希望它返回内容本身,而不是只返回它的大小。

编辑:我想我已经弄清楚了:这不起作用的滚动视图实际上是一个UITableView- 我认为它正在对我屏幕外的单元格进行队列化,这就是它们没有出现的原因。我要做一些测试来确认。

4

2 回答 2

8

尝试使用以下代码对我有用。

for(UIView * subView in myScrollView.subviews ) // here write Name of you ScrollView.
{ 
     // Here You can Get all subViews of your myScrollView.
    // But For Check subview is specific UIClass such like label, button, textFiled etc.. write following code (here checking for example UILabel class).

        if([subView isKindOfClass:[UILabel class]]) // Check is SubView Class Is UILabel class?
        {
            // You can write code here for your UILabel;
        }
}
于 2013-09-04T15:08:22.997 回答
3

tl;dr

It turns out that

NSArray *subviews = [myScrollView subviews];

will indeed return all the subviews in a UIScrollView *myScrollView, even if they are off-screen.


The Details

The problem I was actually having was that the scroll view I was trying to use this on was actually a UITableView, and when a UITableViewCell in a UITableView goes off-screen, it actually gets removed from the UITableView - so by the time I was calling subviews, the cells I was looking for were no longer in the scroll view.

My workaround was to build all of my UITableViewCells in a separate method called by my viewDidLoad, then put all of those cells into an array. Then, instead of using subviews, I just used that array. Of course, doing it this way hurts the performance a little (in cellForRowAtIndexPath you just return the cell from the array, which is slower than the dequeueReusableCellWithIdentifier method that is typically used), but it was the only way I could find to get the behavior I needed.

于 2013-09-04T17:57:42.433 回答