Usage of uiscrollview (occasionally updated)

Source: Internet
Author: User

Let's start with the most basic research and use an example to illustrate how to create a UIScrollView.

Create a view-based project in xcode, open the xib file of viewController in the project, add a uiscrollview to the view, and drag several buttons, textfield, and so on to the scrollview.

In this way, the basic ui framework is complete.

The following is the code:


UIScrollViewDemoViewController. h

#import <UIKit/UIKit.h>@interface UIScrollViewDemoViewController : UIViewController<UITextFieldDelegate,UIScrollViewDelegate> {    IBOutlet UIScrollView * myScrollView;    UITextField * activeField;    CGFloat oldContentOffsetValue;    IBOutlet UITextField * textFieldOne;    IBOutlet UITextField * textFieldTwo;    IBOutlet UITextField * textFieldThree;    IBOutlet UITextField * textFieldFour;    BOOL keyboardShown;    BOOL isNeedSetOffset;    }@property (nonatomic,retain) UITextField * activeField;@end

In the code above, I created five iboutlet variables in the xib file, which are four textfields and one scrollview. Then I can connect them to the xib file and connect them to the corresponding ui.

Other variables are used in the implementation file.


UIScrollViewDemoViewController. m

#import "UIScrollViewDemoViewController.h"@implementation UIScrollViewDemoViewController@synthesize activeField;- (void)dealloc{    [myScrollView release];    [activeField release];    [textFieldOne release];    [textFieldTwo release];    [textFieldThree release];    [textFieldFour release];    [super dealloc];}- (void)didReceiveMemoryWarning{    // Releases the view if it doesn't have a superview.    [super didReceiveMemoryWarning];        // Release any cached data, images, etc that aren't in use.}#pragma mark - View lifecycle// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.- (void)viewDidLoad{    [super viewDidLoad];        textFieldOne.delegate = self;    textFieldTwo.delegate = self;    textFieldThree.delegate = self;    textFieldFour.delegate = self;            myScrollView.contentSize = CGSizeMake(myScrollView.frame.size.width, 1400.0f);    myScrollView.scrollEnabled = YES;    myScrollView.delegate = self;        keyboardShown = NO;    [self performSelector:@selector(registerForKeyboardNotifications)];    }- (void)viewDidUnload{    [super viewDidUnload];    // Release any retained subviews of the main view.    // e.g. self.myOutlet = nil;}- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{    // Return YES for supported orientations    return (interfaceOrientation == UIInterfaceOrientationPortrait);}#pragma mark - UITextField Delegate-(void)textFieldDidBeginEditing:(UITextField *)textField{    activeField = textField;}-(void)textFieldDidEndEditing:(UITextField *)textField{    activeField = nil;}-(BOOL)textFieldShouldReturn:(UITextField *)textField{    [textField resignFirstResponder];    return YES;}#pragma mark -Keyboard Helper Method// Call this method somewhere in your view controller setup code.- (void)registerForKeyboardNotifications{    [[NSNotificationCenter defaultCenter] addObserver:self                                             selector:@selector(keyboardWasShown:)                                                 name:UIKeyboardDidShowNotification object:nil];        [[NSNotificationCenter defaultCenter] addObserver:self                                             selector:@selector(keyboardWasHidden:)                                                 name:UIKeyboardDidHideNotification object:nil];}// Called when the UIKeyboardDidShowNotification is sent.- (void)keyboardWasShown:(NSNotification*)aNotification{    NSLog(@"-------");    if (keyboardShown)        return;        NSDictionary* info = [aNotification userInfo];        // Get the size of the keyboard.    NSValue* aValue = [info objectForKey:UIKeyboardBoundsUserInfoKey];    CGSize keyboardSize = [aValue CGRectValue].size;        // Resize the scroll view (which is the root view of the window)    CGRect viewFrame = [myScrollView frame];    viewFrame.size.height -= keyboardSize.height;    myScrollView.frame = viewFrame;            // Scroll the active text field into view.    CGRect textFieldRect = [activeField frame];    [myScrollView scrollRectToVisible:textFieldRect animated:YES];        oldContentOffsetValue = [myScrollView contentOffset].y;            CGFloat value = (activeField.frame.origin.y+myScrollView.frame.origin.y+activeField.frame.size.height - self.view.frame.size.height + keyboardSize.height)+2.0f;    if (value > 0) {        [myScrollView setContentOffset:CGPointMake(0, value) animated:YES];        isNeedSetOffset = YES;    }    keyboardShown = YES;}// Called when the UIKeyboardDidHideNotification is sent- (void)keyboardWasHidden:(NSNotification*)aNotification{    NSDictionary* info = [aNotification userInfo];        // Get the size of the keyboard.    NSValue* aValue = [info objectForKey:UIKeyboardBoundsUserInfoKey];    CGSize keyboardSize = [aValue CGRectValue].size;        // Reset the height of the scroll view to its original value    CGRect viewFrame = [myScrollView frame];    viewFrame.size.height += keyboardSize.height;    myScrollView.frame = viewFrame;            if (isNeedSetOffset) {        [myScrollView setContentOffset:CGPointMake(0, oldContentOffsetValue) animated:YES];    }    isNeedSetOffset = NO;    keyboardShown = NO;}@end

The Code is a bit long. parse it step by step.

First, initialize the viewDidLoad method:

-(Void) viewdidload {[Super viewdidload]; textfieldone. delegate = self; // set the delegate of textfield, mainly to display and hide the textfieldtwo used by the pop-up keyboard. delegate = self; textfieldthree. delegate = self; textfieldfour. delegate = self; // It is very important to use scrollview. Set the contentsize, which is generally set by setting the size of your scrollview. The following height can be 300 ~ 400 myscrollview. contentsize = cgsizemake (myscrollview. Frame. Size. Width, 140020.f); myscrollview. scrollenabled = yes; // This is yes by default, which is redundant here. Myscrollview. delegate = self; // set the delegate of scrollview. If you want to listen to a rolling event, you can implement its delegate method keyboardshown = no; // a status flag, this method is mainly used to identify the display and hiding status of the keyboard [self defined mselector: @ selector (registerforkeyboardications ications)]; // This method is used to handle the problem when the textfield is blocked by the pop-up keyboard, scroll it to the appropriate position}

Then the corresponding


The registerforkeyboardconfigurications method is used to scroll textfield to an appropriate position.

-(Void) registerforkeyboardconfigurations {// Add yourself as the observer to obtain the notification [[nsicationicationcenter defaultCenter] addObserver: self selector: @ selector (keyboardWasShown :) name: Your object: nil]; // Add yourself as an observer to obtain the notification [[nsicationicationcenter defacenter center] addObserver: self selector: @ selector (keyboardWasHidden :) name: UIKeyboardDidHideNotification object: nil];} // call this method when the keyboard appears-(void) keyboardWasShown :( NSNotification *) aNotification {// if the keyboard is displayed, no repeated operations are required if (keyboardShown) return; // user information dictionary for obtaining keyboard notifications NSDictionary * info = [aNotification userInfo]; // obtain the keyboard size. NSValue * aValue = [info objectForKey: UIKeyboardBoundsUserInfoKey]; CGSize keyboardSize = [aValue CGRectValue]. size; // reset the size of the scrollView CGRect viewFrame = [myScrollView frame]; viewFrame. size. height-= keyboardSize. height; myScrollView. frame = viewFrame; // scroll the currently blocked text field to the appropriate visible position in the view. CGRect textFieldRect = [activeField frame]; [myScrollView scrollRectToVisible: textFieldRect animated: YES]; // records the offset of the current textField to hide the keyboard, restore textField to the original location oldContentOffsetValue = [myScrollView contentOffset]. y; // calculate the appropriate position for textField to scroll to CGFloat value = (activeField. frame. origin. y + myScrollView. frame. origin. y + activeField. frame. size. height-self. view. frame. size. height + keyboardSize. height) + 2.0f; // if the value is greater than 0, scroll is required. if the value is smaller than 0, the current textField is not blocked. if (value> 0) does not need to be rolled) {// scroll textField to the appropriate position [myScrollView setContentOffset: CGPointMake (0, value) animated: YES]; isNeedSetOffset = YES; // change the status flag to scroll} // change the keyboard status flag to show keyboardShown = YES;} // call this method when the keyboard is hidden-(void) keyboardWasHidden :( NSNotification *) aNotification {NSDictionary * info = [aNotification userInfo]; // Get the size of the keyboard. NSValue * aValue = [info objectForKey: UIKeyboardBoundsUserInfoKey]; CGSize keyboardSize = [aValue CGRectValue]. size; // Reset the height of the scroll view to its original value CGRect viewFrame = [myScrollView frame]; viewFrame. size. height + = keyboardSize. height; myScrollView. frame = viewFrame; // if the status flag is scroll, You need to perform the textFiled reset operation if (isNeedSetOffset) {// oldContentOffsetValue records the original position of textField. Reset it to [myScrollView setContentOffset: CGPointMake (0, oldContentOffsetValue) animated: YES];} // reset status flag isNeedSetOffset = NO; keyboardShown = NO ;}

This is a simple scrollview. It is also very common to scroll the blocked content to the appropriate location.

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.