• Using UIScrollView with Auto Layout in iOS


    原文:https://spin.atomicobject.com/2014/03/05/uiscrollview-autolayout-ios/

    Who says you can’t teach an old control some new tricks? The UIScrollView has been around since the beginning of iOS, and there have been many blog posts, Stack Overflow questions, and Apple documentation covering how to set up your content to scroll inside a UIScrollView with the old springs & struts layout system.

    Since the introduction of Auto Layout to iOS, there is a new way you can configure your scrolling content. With Auto Layout, the amount of code you have to write is greatly reduced.
    One of the big pain points with the old way of setting up a UIScrollView was communicating the content size to the scroll view. It was fairly straightforward to calculate your content size if the content in the UIScrollView was an image. But it was not as easy if your scroll view included a mixed bag of buttons, labels, custom views, and text fields. Lengthy code adjustments were needed to reflect constant changes in device rotations and phone size differences.

    In this blog post, I’ll show you how to set up a UIScrollView with Auto Layout that is responsive to portrait and landscape changes. I will also show you how the scroll view can move your content out of the way of the pop-up keyboard.


    Create a Basic Layout in Interface Builder
    I want to give you a sense of what we are building so you can follow along and see how the view is constructed. I created a view with some labels, text fields, and an image. If you want to follow along, I put the entire project on GitHub (https://github.com/woelmer/UIScrollViewWithAutoLayout). Here is what it should look like in portrait and landscape.

    Now let’s get started building the UI. In interface builder, drag a UIScrollView and add it as a sub view of the view controller’s main view. Now add some constraints to your scroll view to place it where you want it in your main view. In my example, the scroll view takes up the whole view, so I added four constraints from the scroll view’s edges to the main view with zero spacing. Your view hierarchy should look like the image to the right.

    The following are the four constraints that I added to get the scroll view constrained to the super view. Your constraints may look different if you do not want the scroll view to occupy the entire screen.

    Use a Single Child View to Hold All of Your Content
    The next step in laying out our controls is to create a single child view of the UIScrollView where we will put all of our content. Using a single child view will simplify the constraints we have to add later. If your content is only a scrolling image in a UIImageView, this can serve as the single child view. In the example below, I gave the child view a name of Content View.

    Our next step is to add constraints from the content view to the scroll view. The change they made to UIScrollView, to support Auto Layout, is that it can automatically calculate the content size if you set up your constraints the right way. It does this in two ways.

    The content view has to be an explicit size (or a placeholder size in interface builder and set at runtime). In other words your content view cannot depend on the scroll view to get its size. It can, however, depend on views outside of the scroll view to get its size. We will use this trick to constrain our content to support portrait and landscape sizes later on. If you are using a scrolling image as your content view, the UIImageView will get its size from the image (you still may need to add placeholder constraints in interface builder to keep it from complaining).

    Even though your content view cannot depend on the scroll view for size, you must add top, bottom, leading, and trailing constraints from your content view to your scroll view. This part is the most confusing because Apple has repurposed the constraints in this case to indicate to the UIScrollView the boundaries of your content and therefore calculate the content size. These special constraints, from your content view to the UIScrollView, do not behave like normal constraints. No matter what constant value you give them, they will not resize your content view. Once they are in place, the UIScrollView can calculate its content size. The only place I could find documentation on this new behavior is in a tech note TN2154 (https://github.com/woelmer/UIScrollViewWithAutoLayout) article by Apple. The only mention is in the section titled “Pure Auto Layout Approach”

    Go ahead and add the top, bottom, leading, and trailing constraints from the content view to the scroll view. When finished, you will notice we are getting some Auto Layout errors. Without any controls inside the content view, or if there are no placeholder width and height constraints on the content view, the scroll view cannot determine the content size.

    The next step is to add whatever content you want to scroll inside the content view and use Auto Layout to constrain the items inside the content view. Make sure you have constraints attached to all four sides of the content view so that it will expand to the size of your content. If you need to, you can increase the simulated size of your view controller in interface builder to give you room to layout all of your scrolling content. To do this click on the view controller, select the size inspector and select Freeform size.

    Supporting Portrait and Landscape Rotations
    I added a few labels and text fields to get started. Now let’s run it to see what happens. Remember that I colored the content view blue and the scroll view yellow.

    Content in the vertical direction — in both portrait and landscape views — is working because the height of my content view is explicit by stacking one control on top of another.

    But as you can see, I have a problem in the horizontal direction. I am fully constrained in the horizontal direction, however since UITextFields do not have an intrinsic content size, without any text inside them, my view is collapsed. I need some way to expand my content view in the horizontal direction to fill the width of the device. I could hard code a width constraint, but that will only work for portrait or landscape and not both.

    The solution is to look outside the scroll view and attach an equal width constraint from the content view to the view controller’s main view.

    Now, when we run, we get the correct behavior in portrait and landscape. The content view will get its width from the main view, and all of the content inside the content view will stretch in the horizontal direction.

    Moving Content under the Keyboard into View
    If you have UITextFields near the bottom of your content view and the keyboard pops up, it blocks the bottom half of your screen; you cannot see what you are typing. The scroll view allows us to scroll the content into view.

    We first need to keep track of which text field is currently being edited. You can do this many different ways, but I chose to add the view controller as a delegate to the UITextFields. In interface builder Ctrl – Drag from each UITextField to the view controller and set it as the delegate.

    Now we can implement a couple of delegate functions to keep track of which field is active. We do this to make sure that the active field is visible when the keyboard pops up.

    weak var activeField: UITextField?

    func textFieldDidEndEditing(textField: UITextField) {
    self.activeField = nil
    }

    func textFieldDidBeginEditing(textField: UITextField) {
    self.activeField = textField
    }

    OBJECTIVE-C
    @property (weak, nonatomic) UITextField *activeField;

    - (IBAction)textFieldDidBeginEditing:(UITextField *)sender
    {
    self.activeField = sender;
    }

    - (IBAction)textFieldDidEndEditing:(UITextField *)sender
    {
    self.activeField = nil;
    }

    Now we need to register for keyboard notifications. In the viewDidLoad function, add the view controller as an observer. Do not forget to unregister from these events when you are transitioning away from your view controller.

    SWIFT
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardDidShow:", name: UIKeyboardDidShowNotification, object: nil)

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillBeHidden:", name: UIKeyboardWillHideNotification, object: nil)

    OBJECTIVE-C

    [[NSNotificationCenter defaultCenter] addObserver:self
    selector:@selector(keyboardDidShow:)
    name:UIKeyboardDidShowNotification
    object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
    selector:@selector(keyboardWillBeHidden:)
    name:UIKeyboardWillHideNotification
    object:nil];

    Finally, add an outlet to your scroll view and implement the keyboard notification selectors. If this code looks familiar, it is based on the solution from Apple’s documentation. I add the height of the keyboard to the scroll view’s content inset so that the scroll view has enough padding at the bottom to scroll the very bottom text field up above the keyboard. As the final step, I check to see if the active text field is visible and scroll the field into view if it is not.

    SWIFT
    func keyboardDidShow(notification: NSNotification) {
    if let activeField = self.activeField, keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
    let contentInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: keyboardSize.height, right: 0.0)
    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets
    var aRect = self.view.frame
    aRect.size.height -= keyboardSize.size.height
    if (!CGRectContainsPoint(aRect, activeField.frame.origin)) {
    self.scrollView.scrollRectToVisible(activeField.frame, animated: true)
    }
    }
    }

    func keyboardWillBeHidden(notification: NSNotification) {
    let contentInsets = UIEdgeInsetsZero
    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets
    }

    OBJECTIVE-C
    - (void)keyboardDidShow:(NSNotification *)notification
    {
    NSDictionary* info = [notification userInfo];
    CGRect kbRect = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];
    // If you are using Xcode 6 or iOS 7.0, you may need this line of code. There was a bug when you
    // rotated the device to landscape. It reported the keyboard as the wrong size as if it was still in portrait mode.
    //kbRect = [self.view convertRect:kbRect fromView:nil];

    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbRect.size.height, 0.0);
    self.scrollView.contentInset = contentInsets;
    self.scrollView.scrollIndicatorInsets = contentInsets;

    CGRect aRect = self.view.frame;
    aRect.size.height -= kbRect.size.height;
    if (!CGRectContainsPoint(aRect, self.activeField.frame.origin) ) {
    [self.scrollView scrollRectToVisible:self.activeField.frame animated:YES];
    }
    }

    - (void)keyboardWillBeHidden:(NSNotification *)notification
    {
    UIEdgeInsets contentInsets = UIEdgeInsetsZero;
    self.scrollView.contentInset = contentInsets;
    self.scrollView.scrollIndicatorInsets = contentInsets;
    }

    This is what it looks like when it’s all working. Once you start editing a text field, the keyboard animates into view, and your scroll view animates the active text field to be above the keyboard. If you would like to try this code out yourself to see it in action, I have the entire project on GitHub.

  • 相关阅读:
    每天一个设计模式(2):观察者模式
    每天一个设计模式(1):策略模式
    每天一个设计模式(0):设计模式概述
    常量池、栈、堆的比较
    常量池小结
    Java虚拟机体系结构分析
    Java并发(3):volatile及Java内存模型
    第一题:Big Countries
    22 高级SQL特性
    21 使用游标
  • 原文地址:https://www.cnblogs.com/qike/p/5662838.html
Copyright © 2020-2023  润新知