Welcome to the Csdn-markdown Editor

Source: Internet
Author: User

This article is translated by Snow(blog) from Appcoda.
Original: A beginner ' s Guide to Uiscrollview
Joyce Echessa

    • Creating scroll View with code
    • Scaling
    • Click Zoom

In iOS, scroll views are used to show that the view content is not fully adaptable to the screen. The Scroll views have two important purposes:

    • Let the user drag the content to the area he wants to show
    • Allow users to display content by zooming in or out by clamping gestures

A control that is often used in iOS apps UITableView is a subclass of Uiscrollview and provides a number of ways to show content beyond the screen.

In this tutorial, we will see many aspects of Uiscrollview, especially creating ScrollView with code or interface Builder, scrolling, zooming, inserting, or embedding ScrollView.

Before reading, download the initial project's include file and we'll use it in the tutorial.

Creating scroll View with code

Scroll views are created just like any other view, whether code or interface Builder. After that, the basic functionality of scrolling can be achieved with minimal configuration.
Scroll view is created or inserted into a controller or other view, complete the configuration of Scroll view requires only two additional steps:

    • you must set the Contentsize property for the size of the scrolling content, which specifies the size of the scrolling area.
    • You must add one or more views for scroll view to show or scroll. These views provide presentation content.

You can arbitrarily configure any visual cues for your program, like horizontal vertical scrolling indicator, drag bounce, zoom bounce, and scrolling direction constraints.
Let's start by creating a scrolling view with the code. Open the Scrollviewdemo project from the file you downloaded, in the story version it contains a view controller connected to the Scrollviewcontroller created in the program. I also included a picture called Image.png, which we'll use later (taken from unsplash.com).

Open Scrollviewcontroller.swift and add the following properties.

var scrollView: UIScrollView!var imageView: UIImageView!

Modify Viewdidload () as shown below.

override func viewdidload () {super () ImageView = Uiimageview (Image:uiimage (named:  "image.png" )) SC Rollview = Uiscrollview (Frame:view.bounds ) Scrollview.backgroundcolor  = Uicolor.blackcolor  () Scrollview.contentsize  = Imageview.bounds  .size  scrollview.autoresizingmask  = Uiviewautoresizing | Uiviewautoresizing scrollview.addsubview  (imageView) View.addsubview  (ScrollView)} 

Above we created a scrolling view and a picture view. A picture view is a child view of a scrolling view. Contentsize sets the size of the scroll range. We set him equal to the size of the picture (x 1500). To make the picture have a black background, we set the background color of the scrolling view to black. We set the Autoresizingmask (auto-Transform size) property of the scrolling view to. Flexiblewidth and. Flexibleheight so that when the device rotates, it can be resized again. Run the app then you can scroll and see the different areas of the picture.

When you run the app, you may find that the initial position of the image is in the upper-left corner.

This is because the initial point of the scrolling view is in (0,0), in the upper-left corner. If you want to change the location of your content when the app starts, you have to change the start point of the scrolling view's range. With the scrolling view, you can change the Uiscrollview Contentoffset property to achieve the same result as changing the initial position because you often need to set this position.

Under the statement that sets the Autoresizingmask property of the scrolling view, paste the following statement.

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

Once again, run the program and you'll see that the scrolling view has been moved to another part of the picture. This allows you to decide what to display in front of the user when the view is loaded.

Scaling

The scrolling view we add allows the user to scroll most of the content that is too large for the screen. This is fine, but it will be better if the user can zoom in on the size of the view.

To support scaling, you must set a delegate for your scrolling view. This delegate must follow the Uiscrollviewdelegate protocol. This protocol must implement the Viewforzoominginscrollview () method and return the Zoomed view.

You should also specify a scale that the user can scale. You do this by setting the Minimumzoomscale and Maximumzoomscale properties of the scrolling view.
Both of them have a default value of 1.0.

Modify the definition of the Scrollviewcontroller class like this.

class ScrollViewController: UIViewController, UIScrollViewDelegate {

Then add the following method to the class.

func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {    return imageView}

Then add the following code at the bottom of the viewdidload ().

scrollView.delegate = self  scrollView.minimumZoomScale0.1scrollView.maximumZoomScale4.0scrollView.zoomScale1.0

In the above code we set the Zoomscale to 1.0 and specify the minimum and maximum values for the scaling factor. When you run the program, it starts with a predetermined scale factor (the scale factor is 1.0). When you use the two-finger clip view, you can adjust up and down in the maximum and minimum scale factor. We set a large number for Maximumzoomscale (4.0), so you can resize the picture to 4 times times its own size. When you turn the scale up, the size of the picture is larger than the original size, and the picture becomes blurred. We'll change it back to the default of 1.0 in the next step.

On top of that, we set the Minimumzoomscale to 0.1, and the resulting picture becomes quite small, leaving a lot of space around the screen. In landscape mode, the blank space next to the picture is larger. We want the picture to fit in a scrolling view so that it takes up enough space to display the picture.

To do this, we calculate the minimum scale by scrolling the view and the size of the picture.

Remove the following three parameters from Viewdidload () first.

scrollView.minimumZoomScale0.1scrollView.maximumZoomScale4.0scrollView.zoomScale1.0

Then add the following method to the class. We get the ratio of width to height and find the smaller one, set it to the minimum zoom ratio. Note that we removed the Maximumzoomscale setting so that it can restore the default setting of 1.0.

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.zoomScale1.0}

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

setZoomScale()

Also Add the following so, the image scales right after the user tries to zoom In/out after a device orientation Chang E.
Also add the following method to make sure that the user can scale the picture correctly after the device changes direction.

viewWillLayoutSubviews() {    setZoomScale()}

Run the app, and now when you zoom in on the picture, he takes up enough space on the screen.

As can be seen from the picture above, scrolling the contents of the view-picture-is the position in the upper left corner of the screen. We want it to be in the middle of the screen.

Add the following method to the class.

Func Scrollviewdidzoom (scrollview:uiscrollview) {Let imageviewsize = ImageView. Frame. SizeLet scrollviewsize = ScrollView. Bounds. SizeLet verticalpadding = Imageviewsize. Height< Scrollviewsize. Height? (scrollviewsize. Height-Imageviewsize. Height) /2:0Let horizontalpadding = Imageviewsize. Width< Scrollviewsize. Width? (scrollviewsize. Width-Imageviewsize. Width) /2:0ScrollView. Contentinset= Uiedgeinsets (top:verticalpadding, left:horizontalpadding, bottom:verticalpadding, right:horizontalpadding)}

This method is called after each scaling action. It tells the delegate that the zoom factor of the scrolling view has changed. In the above code we calculated to put the picture in the middle need to fill or insert the size, the top and bottom of the value, we check whether the height of the picture is smaller than the scrolling view, if it is, fill two view difference of half, if not, we set to 0. We did the same thing in the horizontal direction. Then we set the contentinset of the scrolling view. This is the distance that the content view is inserted from the closed scrolling view.

Run the app and now the content will be placed in the middle when zoomed to the minimum.

Click Zoom

The basic Uiscrollview class supports the pinch-in and pinch-out gestures with a little amount of additional code. But supporting a richer zooming experience using tap detection would rquire more work.
The underlying Uiscrollview class uses a few code implementations to clamp gestures, but using a click to support a better zoom experience requires more work.
The IOS Human Interface guidlines defines a double-tap to zoom on and out. This however assumes some constraints:that the view have a single level of zoom (such as in the Photos application where a Double tap zooms the content up to the maximum zoom and another tap zooms it down to the mimimum),
Two clicks were defined in iOS Human Interface guidelines to achieve zoom. This certainly assumes some constraints:
The view has only one zoom level (for example, in the picture program, two clicks will zoom the content to the maximum scale, then click Will zoom it to the minimum scale) or the effective two clicks will zoom to the maximum scale, after the realization, the next time two clicks will return full screen status. But some programs require more flexibility in handling click-to-Zoom, which is an example of a map program. The map supports two click-to-zoom, and the extra two clicks will zoom deeper. To scale a larger scale, the map is touched with two fingers, and when two fingers are close together, zoom to the minimum.

In order for your program to support click-to-zoom, you need to implement the Uiscrollview delegate method in the class gesture processing Viewforzoominginscrollview (), which is responsible for tracking the number of fingers and the number of clicks. When it finds a click, double click, click two times, it will respond accordingly. When you click two times and have two finger clicks, the code is implemented to scale appropriately.

For our program, we will perform a click two times, if the current is the minimum scale, then zoom to the maximum, and vice-versa to the smallest. This is the same as what you see in the picture program.

Add the following two methods to the class.

func setupGestureRecognizer() {    "handleDoubleTap:")    doubleTap.numberOfTapsRequired2    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)    }}

Then call at the bottom of the viewdidload () below.

setupGestureRecognizer()

In the code above, we added a gesture recognizer for the scrolling view. It recognizes that the user clicks on the screen two times and we handle the zoom depending on the current zoom situation.

To run the app, you should be able to zoom by clicking two times.

Welcome to the Csdn-markdown Editor

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.