Wednesday, September 26, 2012

Change a View to a ScrollView in Xcode Interface Builder

I recently needed to change UIView to a UIScrollView, then embed that ScrollView into a View. I won't go into the underlying code required to manipulate scrollViews. I am interested here in getting the UI correct with InterfaceBuilder.

First, with Xcode IB, open the storyboard and locate the View you want to change. With the Utilities View (the rightmost button of the View group on the Xcode Toolbar), show the Identity Inspector.

Change the Class under Custom Class from UIView to UIScrollView.

Since you need to embed the scrollView into a View, you can manually add a View under into the parent View Controller visual object or wait and use the Xcode Menu > Editor > Embed In > View command later. If you do it now, you will need to adjust the ScrollView position in the View window.

The "View" is now a scrollView but the Attribute Inspector still indicates it is a View.

We want the Attribute Inspector to look like this:

To get this, in Xcode, use right-click on the storyboard, and Open As > Source Code. 

Now, in the XML source, search for UIScrollView. You will find something like this: (the !-- and -- are XML comments that I added)

Change that to the following: (the !-- and -- are XML comments that I added)

Note that the id is the same.

Also, change the associated /view to /scrollView at the bottom of this XML clause.

That's it.

If you want to now , use the Embed In command to embed the ScrollView in a View.


Scott Barden said...

Thanks for this. I didn't realise about the "Embed In | View" option. So I tried selecting all the components within the view and then chose Embed In -> Scroll View. The result was a new scroll view embedded in my existing view, with all the existing child views correctly positioned inside the new scroll view. Even easier I think :)

ehsan moradi said...

thanks allot i just change to

thanx again

ehsan moradi said...

what :D where is my code ??
i just type code at last comment :(

Asli Cetinel said...

Thanks a lot, really helped :) :)