简体   繁体   中英

iOS: Changing subclass from UIView to UIScrollView in a storyboard

I have created a storyboard based project. In one of the view controller's view requires some extra elements to be placed which results in increasing the view height such that the view must now be scrollable. Is it possible to simply change the class type of UIView to UIScrollView in storyboard? Will it really convert the top level UIView to UIScrollView ? Just looking for a quick and easy way of doing this without much changes.

Thanks

You can open storyboard as an xml source code file, find view object and replace it with scrollview. Right-click on .storyboard file in Xcode and choose Open As → Source Code. Then search for your scene's xml snippet (for example, Cmd+F and type controllers name). Top view object will look like this:

<view key="view" contentMode="scaleToFill" id="Jjm-HD-A8W">
  ...
  (suviews and constraints)
  ...
</view>

Change view element to scrollView (don't forget the closing tag):

<scrollView key="view" contentMode="scaleToFill" id="Jjm-HD-A8W">
  ...
  (suviews and constraints)
  ...
</scrollView>

Then open .storyboard with the Interface Builder. Your view now became a scrollview.

This method has two advantages: you don't loose any constraints and you see all scrollview specific properties in the attributes inspector.

您必须将UIView类型更改为UIScrollView (身份检查器),并在控制器viewDidLoad方法中通过将视图转换为UIScrollView来为视图分配contentSize

[(UIScrollView *)self.view setContentSize:CGSizeMake(320, 700)];

There's actually a much better way to do this.

  1. Toggle open the UIView in the StoryBoard and cut to your clipboard anything inside it.
  2. Delete the UIView .
  3. Insert a UIScrollView object into your StoryBoard.
  4. Paste from your clipboard into this new object.

This method will preserve all delegate and IBOutlet settings you've configured for the things inside the view.

An easier method is to just use a scroll view and set the contentsize to be the same size as the frame - so there is no scrollable area. eg

scrollview.contentsize = CGSizeMake(320,480);

then when you need to make your view larger, simply update this as required. You will need to ensure that bounce is turned off otherwise you'll still be able to drag around the scrollView though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM