darksky
darksky

Reputation: 21059

Views in ScrollView

I am trying to create a UIScrollView programatically. I have a scrollView for that ViewController. Here is how I instantiate it in loadView:

    CGRect fullScreenRect = [[UIScreen mainScreen] applicationFrame];
    self.scrollView = [[UIScrollView alloc] initWithFrame:fullScreenRect];
    self.scrollView.contentSize = CGSizeMake(self.view.frame.size.width, self.view.frame.size.height);

I then some items onto it, and then add it to view in loadView as follows:

[self.scrollView addSubview:self.searchBar];
[self.scrollView addSubview:button];
[self.view addSubview:self.scrollView];

So far everything should be fine. However, in other functions, I will be adding ImageViews and then I will need to set the scrollview's content size. The way I do it is just use [self.scrollView addToSubView:image] and when I want to edit the content size of the scrollview, I do it as follows:

// Calculate scroll view size
float sizeOfContent = 0;
for (int i = 0; i < [self.scrollView.subviews count]; i++) {
    UIImageView *view =[self.scrollView.subviews objectAtIndex:i];
    sizeOfContent += view.frame.size.height;
    [view release];
}

// Set content size for scroll view
self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width, sizeOfContent);

I keep getting an EXC_BAD_ACCESS error in the main.m class.

I suspect that the problem is with retaining the actual scrollView since I think scrollView is not retaining the same object that is a subview of view.

Any suggestions? Thanks in advance!

Upvotes: 0

Views: 336

Answers (1)

Mridul Kashatria
Mridul Kashatria

Reputation: 4197

If you have defined self.scrollView as @property(nonatomic, retain) then first wrong thing is the line;

self.scrollView = [[UIScrollView alloc] initWithFrame:fullScreenRect];

It sets the retain count of scrollView to 2, which is not what you expect. alloc retained properties like this,

scrollView = [[UIScrollView alloc] initWithFrame:fullScreenRect];

I think your BAD_ACCESS error comes from here;

for (int i = 0; i < [self.scrollView.subviews count]; i++) {
   UIImageView *view =[self.scrollView.subviews objectAtIndex:i];
   sizeOfContent += view.frame.size.height;
   [view release];
}

Why are you releasing view? You did not alloc it, so there is no reason to release it. Remove the [view release] line and check again.

Upvotes: 1

Related Questions