Ali
Ali

Reputation: 9994

Add a scrollView to a view in .xib file

I have an xib file includes a UIView and a UIScrollView.

Inside my UIView, I have another UIView (the while screen in the middle), and I want to add my scrollView to it programmatically.

The reason is one time I want to add a scrollView there and another time I want to add a mapView.

What I did is like this:

CGRect frame = self.view.bounds;
    self.scrollView = [[UIScrollView alloc] initWithFrame: frame];
    CGSize pagesScrollViewSize = self.view.frame.size;
    self.scrollView.contentSize = CGSizeMake(pagesScrollViewSize.width * self.pageImages.count, pagesScrollViewSize.height);

I also need to set the delegate for the UIScrollView.

I could not make it work. this is my error:

-[UIScrollView setPageId:]: unrecognized selector sent to instance 0x7dd84e0
2012-10-06 00:56:17.373 testN[3525:c07] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIScrollView setPageId:]: unrecognized selector sent to instance 0x7dd84e0'

I also don't know where should I connect the scrollView delegate. can you help me?

Upvotes: 0

Views: 2760

Answers (2)

Ali
Ali

Reputation: 9994

I can do that successfully by adding a UIScrollView in the interface builder and then set the delegate and file owner from there.

I just should note that since I want to add the UIView to a ViewController in storyboard this code will not work:

NSArray *views = [[NSBundle mainBundle] loadNibNamed:@"OfferView" owner:self options:nil];
UIView *newPageView = [views lastObject];

I should use:

UIView *newPageView = [views objectAtIndex:0];

Upvotes: 1

Jason Cabot
Jason Cabot

Reputation: 151

The error you're getting isn't in the code that you have pasted, it's because you probably have some code such as self.scrollView.pageId = ... somewhere else

Regardless of that, to help you achieve the effect you want you should probably add IBOutlet references for the MKMapView, UIScrollView and white UIView in the middle of the screen to your view controller.

You can also set the delegate of the scrollView in your xib file by right clicking on it and dragging the circle next to delegate (under Outlets) to the Files Owner (assuming the files owner is a UIViewController that implements UIScrollViewDelegate)

Then in viewDidLoad you'd have something like this

- (void)viewDidLoad {
    [super viewDidLoad];

    self.scrollView.contentSize = self.scrollView.frame.size;
    self.scrollView.frame = self.whiteCenterView.bounds;
    [self.whiteCenterView addSubview:self.scrollView];
}

You shouldn't alloc/init a scroll view manually in code as you already have it there in the xib file and it will already be automatically created by the time viewDidLoad is called in your controller.

Upvotes: 3

Related Questions