Reputation: 9426
I'm trying to use a horizontal-paging UIScrollView
in my custom UITableViewCell
using Autolayout. I've successfully added the UIScrollView
to the cell with all the proper constraints.
My problem arises when I try to load the UIScrollView
with views. I'm overriding the custom cell's layoutSubviews
method and loading the ScrollView's views there because it's the only method I could find where Autolayout's constraints had been loaded. Thus, giving me accurate references to the ScrollView's size.
-(void)layoutSubviews {
[super layoutSubviews];
for(int i=0; i<self.scrollArray.count; i++) {
CGRect frame;
CGFloat width = self.theScrollView.frame.size.width;
frame.origin.x = width * i;
frame.origin.y = 0;
frame.size = self.theScrollView.frame.size;
UIView *subview = [[UIView alloc] initWithFrame:frame];
[subview addSubview:[self.scrollArray objectAtIndex:i]];
[self.theScrollView addSubview:subview];
}
CGSize contentSize = CGSizeMake(self.theScrollView.frame.size.width * self.scrollArray.count, self.theScrollView.frame.size.height);
self.theScrollView.contentSize = contentSize;
self.theScrollView.contentOffset = CGPointMake(0, 0);
}
However, layoutSubviews
is called multiple times on my cell and thus adding more subviews than necessary to my UIScrollView
. Is there a better method to load my subviews in that I'm not aware of? Or is there a way to use layoutSubviews
but make sure my subviews are only loaded once into the UIScrollView
?
Upvotes: 0
Views: 255
Reputation: 2343
Move the part where you add the subviews to the scrollview to where you set the scrollArray and added the subviews to subview array property. In layoutsubviews, you should deal with setting frame only.
- (void)layoutSubviews
{
[super layoutSubviews];
// self.theScrollView.frame = Make sure you set the scroll view frame;
for(int i=0; i<self.scrollArray.count; i++)
{
UIView *aView = [self.scrollArray objectAtIndex:i];
aView.frame = CGRectMake(self.theScrollView.frame.size.width * i, 0, self.theScrollView.frame.size.width, self.theScrollView.frame.size.height);
}
self.theScrollView.contentSize = CGSizeMake(self.theScrollView.frame.size.width * self.scrollArray.count, self.theScrollView.frame.size.height);
self.theScrollView.contentOffset = CGPointMake(0, 0);
}
- (void)partWhereYouSetScrollArray
{
for(int i=0; i<self.scrollArray.count; i++)
{
[self.theScrollView addSubview:[self.scrollArray objectAtIndex:i]];
}
}
- (void)prepareForReuse
{
[super prepareForReuse];
[[self.theScrollView subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];
[self.scrollArray removeAllObjects];
}
Upvotes: 1