Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
362 views
in Technique[技术] by (71.8m points)

ios - Add a ScrollView to existing View

I'm developing a little app in Swift 2.0. I have a View with the following hierarchy:

enter image description here

Now, the elements placed in this view can't be displayed entirely in it, so I would like to use a ScrollView in order to be able to scroll all the content.

How I can embed all the content of my Viewto a new ScrollView? Can I do this programmatically by code?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

UPDATE: There's an easier way to do this which I didn't know when I posted this answer

1) Go to the viewcontroller on the storyboard and click on something in it and press Command + A. This will select all the elements in the view.

2) Go to Editor -> Embed In -> Scroll View. This will embed all the labels, views, etc into a scrollView.

3) Select the scrollview that you just embedded. Press Control and drag it to the respective class file of the viewcontroller and create an outlet scrollView.

4) Add this to your viewDidLoad()

scrollView.contentSize = CGSizeMake(self.view.frame.width, self.view.frame.height+100)

Make sure the height for the contentSize is more than the size of your view.

ADDING SCROLLVIEW MANUALLY

1) Drag and drop a scrollview from the Object Library onto your viewcontroller in the storyboard and create an outlet to your program as 'scrollView'.

2) Click on your viewcontroller and go to the size inspector and note down the width and height.

3) Click on your scrollview and set the width and height the same as the viewcontroller. and set the X and Y values to 0

4) Click on the scrollView and drag it a little bit to the side

5) Press Command+A to select all the elements including scrollView. Press Command and click on the scrollView to deselect the ScrollView

6)You will have all the elements except the scrollView selected now. Now click and drag them into the scrollView.

Moving into scrollView

7) Now click on the scrollView and set the X and Y values to 0 from the Size Inspector.

8) Add this to your viewDidLoad()

scrollView.contentSize = CGSizeMake(self.view.frame.width, self.view.frame.height+100)

Make sure the height for the contentSize is more than the size of your view.

That should create a scrollView for your view. Some of the elements might be in a slightly different position. You can easily fix them by moving them on your storyBoard.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...