Uiscrollview Beginner's Tutorial

Source: Internet
Author: User

In iOS development, scrolling view (Uiscrollview) is typically used to display a view with a larger content size than the screen size. The scrolling view has the following two main functions:

    • Lets users see what they want by dragging and dropping gestures

    • Allows users to zoom in or out of a watch by pinching gestures

Table Views (UITableView), which are common in iOS apps, inherit from the scrolling view and can therefore display more content by scrolling up and down.

In this tutorial, we'll discuss a number of aspects of scrolling view, including: Creating a scrolling view, implementing scrolling and zooming, and nesting using scrolling views using both pure code and visual programming.

Before continuing, please download the resource file required for the sample code in this article, as described in: Resource file address. (Note: The original source file address needs FQ access, I have been transferred to GitHub, see here)

Create Uiscrollview using pure code

Uiscrollview, like other views, can be created in both pure code and visual programming. After creation, only a small amount of additional setup is required to allow the Uiscrollview to get basic scrolling functionality.

Uiscrollview, like other views, should be managed by a single controller or added to a view level. The following two-step setup is required for Uiscrollview to complete the scrolling function:

    • You must set the Contentsize property of the Uiscrollview, which provides the size of the content of the Uiscrollview, which is the size of the area that can be scrolled.

    • You must add one or more sub-views for Uiscrollview to display and scroll, which provide the content that Uiscrollview displays.

You can also set some of the Uiscrollview's display effects based on your application's specific needs, such as whether to show horizontal and vertical scrollbars, scrolling elasticity, scaled elasticity, and allowable scrolling direction.

Next we'll create a uiscrollview in the code. Open the Scrollviewdemo project in the downloaded resource file. It is a simple single View application project, except that the type of the root controller in the storyboard is bound to a new controller called Scrollviewcontroller, and a picture is added to the project that we want to use. The picture name is Image.png.

Next open the Scrollviewcontroller.swift file and add the following code.

12 varscrollView: UIScrollView!varimageView: UIImageView!

Modify the Viewdidload () method as shown in the following code.

12345678910 override func viewDidLoad() {    super.viewDidLoad()    imageView = UIImageView(image: UIImage(named: "image.png"))    scrollView = UIScrollView(frame: view.bounds)    scrollView.backgroundColor = UIColor.blackColor()    scrollView.contentSize = imageView.bounds.size    scrollView.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight    scrollView.addSubview(imageView)    view.addSubview(scrollView)}

The code above creates a uiscrollview and uiimageview,uiimageview that are set to Uiscrollview as a child view. The Contentsize property controls the size of the scrolling area, and we set it to be as large as the size of the picture (2000x1500). We set the background color of the scrolling view to black so that the picture scrolls like a black curtain. We set the Autoresizingmask property of the scrolling view to. flexiblewidth and. Flexibleheight so that it automatically adapts to the new width and height after the device rotates. To run the current app, you can already scroll through the pictures by dragging and dropping gestures.

When you start the app, you'll see that the initial display area of the image is the upper-left part of it.

This is because the beginning of the bounds of the scrolling view defaults to (0, 0), which represents the upper-left corner. If you want to change the position shown after startup, you need to change the starting point of the bounds of the scrolling view. Because this requirement is often mentioned, Uiscrollview specifically provides an attribute contentoffset to implement this requirement.

Add the following statement in your code, and note that after you set the Autoresizingmask statement.

1 scrollView.contentOffset = CGPoint(x: 1000, y: 450)

Rerun the app and you'll see that the other part of the picture is displayed at the beginning instead of the upper-left corner. This way you can determine what will be displayed after the program starts.

Scaling

We have added a Uiscrollview and can allow users to view content larger than the screen size by dragging and dropping. Pretty good, but a better experience if the view can be scaled.

To support the zoom feature, you must set up a proxy for Uiscrollview, and the agent must comply with the Uiscrollviewdelegate protocol, and the agent needs to implement the Viewforzoominginscrollview () method, This method returns the view that you want to be scaled.

You should also set a scale for scaling, which can be achieved by Uiscrollview the Minimumzoomscale and Maximumzoomscale properties, and their default values are 1.0.

Change the definition of Scrollviewcontroller according to the following code:

1 class ScrollViewController: UIViewController, UIScrollViewDelegate {

Then add the following code:

123 func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {    returnimageView}

Next, add the following code at the end of the Viewdidload () method:

1234 scrollView.delegate = self    scrollView.minimumZoomScale = 0.1scrollView.maximumZoomScale = 4.0scrollView.zoomScale = 1.0

In the above code, we set the Zoomscale to 1.0 and then set the maximum and minimum scale for the scaling. After the program is run, it will be displayed according to the original size of the picture (because Zonmscale is 1.0), when you use the pinch gesture to manipulate the picture, you will find that the picture can be scaled. We set the Maximumzoomscale to 4.0, so the maximum image can only be enlarged to 4 times times. You will also find that the image will become blurry after zooming in 4 times times, so we will reset it to 1.0.

From the above picture we can find that we previously set the Minimumzoomscale to 0.1 is too small, the screen out a lot of free space. In landscape mode, the idle area looks larger. We want the picture to be able to match the screen in a certain direction, so that the picture can be both fully displayed and the screen free space is minimized.

To achieve this effect, you must calculate the minimum scale by the size of the picture and Uiscrollview.

First remove the following three lines of code in the Viewdidload () method:

123 scrollView.minimumZoomScale = 0.1scrollView.maximumZoomScale = 4.0scrollView.zoomScale = 1.0

Add the following method to the Controller class. In the method, we calculate the ratio of the height and width of the image to the Uiscrollview, and set the minimum scale to the smaller of the two. Note that we have removed the Maximumzoomscale setting, so its default value is 1.0.

12345678 func setZoomScale() {    let imageViewSize = imageView.bounds.size    let scrollViewSize = scrollView.bounds.size    let widthScale = scrollViewSize.width / imageViewSize.width    let heightScale = scrollViewSize.height / imageViewSize.height    scrollView.minimumZoomScale = min(widthScale, heightScale)    scrollView.zoomScale = 1.0}

This method is called at the end of the Viewdidload () method:

1 setZoomScale()

This method also needs to be called in the Viewwilllayoutsubviews () method, so that when the user changes the screen orientation, the picture is still the correct size.

123 override func viewWillLayoutSubviews() {    setZoomScale()}

Run the program, and now you'll see that no matter how small you zoom, the picture will show up and fill up the remaining space as much as possible.

We can see that the picture is positioned in the upper left corner of the screen and we want it to be placed in the middle of the screen.

Add the following method in your code.

1234567 func scrollViewDidZoom(scrollView: UIScrollView) {        let imageViewSize = imageView.frame.size        let scrollViewSize = scrollView.bounds.size        let verticalPadding = imageViewSize.height < scrollViewSize.height ? (scrollViewSize.height - imageViewSize.height) / 2 : 0        let horizontalPadding = imageViewSize.width < scrollViewSize.width ? (scrollViewSize.width - imageViewSize.width) / 2 : 0        scrollView.contentInset = UIEdgeInsets(top: verticalPadding, left: horizontalPadding, bottom: verticalPadding, right: horizontalPadding)    }

This method is called when zooming, which notifies the agent that the scaling of the Uiscrollview has changed. In the above method, we calculated the inner spacing of the picture in the scrolling view, so that the picture is always in the middle of the screen. For the padding in the top and bottom directions, we first determine whether the height of the picture view is less than the height of the scrolling view, and if so, set the margin to be half the difference between the two, otherwise set to 0. Horizontal spacing We calculate in the same way. The padding for all directions is then set through the Contentinset property, which represents the distance uiscrollview the contents of the Uiscrollview itself.

Run the program and you'll find that when you zoom out, the picture stays in the middle of the screen.

To zoom by double-clicking

Uiscrollview By default only supports pinch gestures for zooming, and if you want to zoom by double-clicking, you need to do some extra setup yourself.

The iOS HMI guide describes the effect of zooming by double-clicking the gesture. Scaling with double-tap gestures requires a certain premise: the view you want to scale can only be scaled back and forth between the maximum and minimum two fixed values, just like the official Apple album app, when you double-click the picture, the picture zooms to its maximum, and when you double-click it, the picture shrinks to a minimum, Or you can use a continuous double-click to make the view a little bit maximum, and then double-click again, the view to full-screen display. But most applications require more flexible double-click scaling, such as a map app, which zooms in when you double-click, and continues to zoom in and out, and you can use a two-finger pinch gesture to zoom out.

To implement the double-click Zoom function in your program, you need to listen for uiscrollview gestures and handle them. In our program, we will imitate the effect of Apple's official album app, Zoom to the maximum when you double-click, and zoom out to the minimum when you double-click.

Add the following two methods to your code.

123456789101112 func setGestureRecognizer() {    let doubleTap = UITapGestureRecognizer(target: self, action: "handleDoubleTap:")    doubleTap.numberOfTapsRequired = 2    scrollView.addGestureRecognizer(doubleTap)}func handleDoubleTap(recognizer: UITapGestureRecognizer) {    if(scrollView.zoomScale > scrollView.minimumZoomScale) {        scrollView.setZoomScale(scrollView.minimumZoomScale, animated: true)    else{        scrollView.setZoomScale(scrollView.maximumZoomScale, animated: true)    }}

The above method is then called at the end of the Viewdidload () method.

1 setGestureRecognizer()

In the above code, we added a double-tap gesture for Uiscrollview, and then judged the image to zoom in or out, based on the current magnification of the image.

Run the program and you will see that you can zoom the image by double-clicking the gesture.

Creating Uiscrollview with visual programming

Using storyboard can be implemented in the same way as we do with the code above, and it is simpler and less code.

In the Main.storyboard file, drag a new view controller and set it as the initial controller (you can either drag the arrows onto the new controller or the IS Initial View Controller check box in the Properties tab).

Drag a Uiscrollview to the new controller, and then set its edges to always stick to the screen.

Then drag a uiimageview into the Uiscrollview just now and set its edge to sticky uiscrollview.

Remember that Uiscrollview needs to know the size of its content before scrolling can be implemented. When you set a picture for Uiimageview, the content size of Uiscrollview is automatically set to the size of the picture.

In the Properties tab of Uiimageview, set the Image property to Image.png, and then resolve the problem of automatic layout by updating the frames. Run the program, you will find that the picture has been implemented scrolling display, and did not hit a line of code. You can also see which properties can be set in the Properties tab of the Uiscrollview, such as setting the maximum and minimum zoom ratios.

If you want to implement scaling, you still need to go through the code, set up the proxy, and implement the Viewforzoominginscrollview () method, as we did before, and don't repeat it again.

Nested use of Uiscrollview

You can nest another uiscrollview in one Uiscrollview, and two uiscrollview can be scrolled in the same direction or in different directions. For example code for this section, use the Nestedscrollviews project.

Uiscrollview nesting in the same direction

Uiscrollview nesting in the same direction refers to a uiscrollview, which has another uiscrollview as a child control, and they scroll in the same direction. You can do this with nesting in the same direction, such as adding multiple sets of data to differentiate in Uiscrollview, and you can also use it to realize the parallax effect of two uiscrollview simultaneously scrolling. In our example, we set different scrolling speeds for the two uiscrollview in the same direction, thus achieving the Parallax effect when scrolling.

Open the storyboard file in the Nestedscrollviews project and you will see two uiscrollview, called foreground and background, respectively. A uiimageview was added to the background, and set the picture to Image.png,foreground inside add some tags and a container for the UIView, these tags just to facilitate our view of the scroll, the container view we will be used in the next section of the content.

Our interface so even if the build is complete, now run the program, you will find only the foreground view is scrolling, while the background view is not moving. Next we are going to implement background scrolling, and realize the scrolling parallax effect.

First connect the foreground and background two Uiscrollview to the controller, after which the code looks like this:

12 @IBOutlet weak varbackground: UIScrollView!@IBOutlet weak varforeground: UIScrollView!

We need to know how long the foreground view has scrolled to calculate how far the background view needs to be scrolled. So we need to set up a proxy for the foreground view to listen for its scrolling.

1 class ViewController: UIViewController, UIScrollViewDelegate {

Set the proxy for the foreground view in the Viewdidload () method.

1 foreground.delegate = self

Then implement the following proxy methods.

123456 func scrollviewdidscroll (Scrollview: uiscrollview)  { &NBSP;&NBSP;&NBSP;&NBSP; let foregroundheight = foreground.contentsize.height - cgrectgetheight ( foreground.bounds) &NBSP;&NBSP;&NBSP;&NBSP; let  percentagescroll = foreground.contentoffset.y / foregroundheight &NBSP;&NBSP;&NBSP;&NBSP; let backgroundheight = background.contentsize.height -  Cgrectgetheight (background.bounds) &NBSP;&NBSP;&NBSP;&NBSP; background.contentoffset = cgpoint (x: 0, y: backgroundheight  * percentagescroll) }

In the above code, we get the maximum height that the foreground view can scroll, divide it by the current scrolling distance to get the scrolling scale, and then get the maximum height that the background view can scroll, multiplying it by the scrolling scale, You can get the distance background should scroll. Run your program, and when you scroll you will find that the foreground and background two views are scrolling, and the background view scrolls faster and thus has a parallax effect.

Uiscrollview Nesting in cross direction

Uiscrollview nesting in a cross direction refers to a uiscrollview, which has another uiscrollview as a child control, and their scrolling direction is exactly 90 °, so let's show this.

In the Nestedscrollviews project, you'll find a container View in foreground that we'll use to set our horizontal scrolling uiscrollview.

Drag a new controller into the storyboard, control-drag from container view to the new controller, and select embed mode. Then select the controller, set its size option to freeform and set its height to 128, because container view is 128.

Drag a uiscrollview into the new controller and set its edges to always adhere to the parent control. Then drag a 70x70 UIView in the Uiscrollview, set its background color to gray to make it easier for us to watch, then copy multiple, from left to right in the Uiscrollview. You don't need to set the exact location of each uiview, and then I'll show you how to do it. Now our controller interface should look like this.

Select the leftmost uiview to add the upper and left constraints, and then widen and height constraints.

Then select the rightmost uiview to add its top, right, width, and height constraints.

Next, select our Uiscrollview, then click Editor > Resolve Auto Layout issues > All views > Add Missing Constraints in the menu bar above. So all our uiview are added to the constraints. Run your program, scroll vertically to the bottom, and you'll see our container View, where you can scroll horizontally through the contents. , I set the background color of the controller's own view to transparent, so the effect you see is this.

Our tutorial this is over, and does not contain all aspects of uiscrollview, but I hope that through this tutorial can let you have a preliminary understanding of Uiscrollview, more uiscrollview knowledge, you can view the official Apple document: Scroll View Programming Guide.

Uiscrollview Beginner's Tutorial

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.