iOS Tutorial : Preview Paging

Introduction

Paging is a widely used functionality within iOS applications. Paging is build by using an UIScrollView. While scrolling to the left or the right, the user will swipe the application content from page to page.

Besides this normal behaviour of a scrollview, an iOS developer could also like to build a pager like the Safari Page Preview to enhance the users experience:

Implementation

To be able to create such a paging scrollview, follow the three steps below:

Step 1:

Create a UIView

CGRect viewFrame = CGRectMake(0, 0, 300, 100);UIView *view = [[UIView alloc]initWithFrame:viewFrame];[view setClipsToBound:YES];

Step 2:

Create a scrollView with a width of 250, and position it in the middle of the view

CGRect scrollFrame = CGRectMake(25, 0, 250, 100);UIScrollView *scrollView = [UIScrollView alloc] initWithFrame:scrollFrame];[scrollView setClipsToBound:NO];

CGSize scrollContentSize = CGSizeMake(500, 100);

[scrollView setContentSize:scrollContentSize];

[view addSubview:scrollView];

When ClipsToBound is set to NO, the content of the scroll view will be visible outside of the scroll views own frame. The same applies to the view, set ClipsToBound to YES, so the content of the scroll view will not appear outside of that view.

Having implemented this, it should also be possible to scroll the view while a user touches the view outside of the scroll view.

Step 3:

Create a method for the view that recognizes touches:

-(UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {UIView *child = [super hitTest:point withEvent:event];if (child == self) {

return self.scrollView;

}

return child;

}

This method allows a user to scroll the pages within the scroll view, without touching the scroll view itself.

Conclusion

Standard paging is not always good enough to create a great user experience. Using a tiny bit of code to create an additional functionality for existing components, helps you to reach that experience.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s