Implementation of menu scroll view for iOS and ios scroll View

Source: Internet
Author: User

Implementation of menu scroll view for iOS and ios scroll View

Menu scroll view is also a common feature in the project development process.

 

The implementation result is as follows:

When the total length of the number of menus exceeds the width of a screen, the width of each text is calculated. If not, only one screen is evenly divided. When a menu item is clicked, the scrolling view position is adjusted accordingly; the code will be pasted below;

1: Contents of the controller. h file

/// MyScrollerViewController. h // testTest /// Created by wujunyang on 16/1/22. // Copyright©2016 wujunyang. all rights reserved. // # import <UIKit/UIKit. h >@protocol upload <NSObject> @ optional-(void) itemDidSelectedWithIndex :( NSInteger) index; @ end @ interface myScrollerViewController: UIViewController @ property (nonatomic, weak) id <authorization> delegate; @ property (nonatomic, assign) NSInteger currentIndex; @ property (nonatomic, copy) NSArray * myTitleArray; @ end

Note: The delegate created here is mainly used to upload the corresponding action when you click an event and transfer the corresponding menu index value to facilitate other operations.

2:. m controller content

# Import "myScrollerViewController. h "# define SCREEN_WIDTH ([UIScreen mainScreen]. bounds. size. width) # define SCREEN_HEIGHT ([UIScreen mainScreen]. bounds. size. height) # define attributes [UIFont systemFontOfSize: 18.f] # define attributes 50 # define attributes SCREEN_WIDTH @ interface myScrollerViewController () // scroll view @ property (strong, nonatomic) UIScrollView * myScrollView; // scroll the underline @ property (s Trong, nonatomic) UIView * line; // All Button sets @ property (nonatomic, strong) NSMutableArray * items; // All Button width sets @ property (nonatomic, copy) NSArray * itemsWidth; // The width of the selected Front (used to calculate whether a screen is exceeded and if no screen is exceeded) @ property (nonatomic, assign) CGFloat selectedTitlesWidth; @ end @ implementation myScrollerViewController-(void) viewDidLoad {[super viewDidLoad]; self. automaticallyAdjustsScrollViewInsets = NO; self. view. backgroundColor = [UIColor whiteColor]; // initialize the array if (! Self. myTitleArray) {self. myTitleArray = @ [@ "news", @ "NBA", @ "finance", @ "technology", @ "software company", @ "Fitness ", @ "Excellent Digest"];} self. items = [[NSMutableArray alloc] init]; self. itemsWidth = [[NSArray alloc] init]; // initialize the scroll if (! Self. myScrollView) {self. myScrollView = [[UIScrollView alloc] initWithFrame: CGRectMake (0, 64, NAV_TAB_BAR_Width, NAV_TAB_BAR_HEIGHT)]; self. myScrollView. backgroundColor = [UIColor redColor]; self. myScrollView. showsHorizontalScrollIndicator = NO; self. myScrollView. showsVerticalScrollIndicator = NO; [self. view addSubview: self. myScrollView];} // value assignment and calculation scroll _ itemsWidth = [self getButtonsWidthWithTitles: self. myTitleArray]; CGFloat contentWidth = [self contentWidthAndAddNavTabBarItemsWithButtonsWidth: _ itemsWidth]; self. myScrollView. contentSize = CGSizeMake (contentWidth, 0); self. currentIndex = 0;}/*** @ author wujunyang, 16-01-22 13:01:45 ** @ brief computing width ** @ param titles <# titles description #> ** @ return <# return value description #> ** @ since <# version number #> */-(NSArray *) authorization :( NSArray *) titles; {NSMutableArray * widths = [@ [] mutableCopy]; _ selectedTitlesWidth = 0; for (NSString * title in titles) {CGSize size = [title boundingRectWithSize: CGSizeMake (CGFLOAT_MAX, CGFLOAT_MAX) options: NSStringDrawingUsesLineFragmentOrigin attributes :@{ NSFontAttributeName: TABBAR_TITLE_FONT} context: nil]. size; CGFloat eachButtonWidth = size. width + border f; _ border + = eachButtonWidth; NSNumber * width = [NSNumber numberWithFloat: eachButtonWidth]; [widths addObject: width];} if (_ selectedTitlesWidth <Border) {[widths removeAllObjects]; NSNumber * width = [NSNumber numberWithFloat: NAV_TAB_BAR_Width/titles. count]; for (int index = 0; index <titles. count; index ++) {[widths addObject: width] ;}} return widths;}/*** @ author wujunyang, 16-01-22 13:01:14 ** @ brief initialize the Button ** @ param widths <# widths description #> ** @ return <# return value description #> ** @ since <# version number #> */-(CGFloat) contentWidthAndAddNavTabBarItemsWithButtonsWidth :( NSArray *) widths {CGFloat buttonX = 0; for (NSInteger index = 0; index <widths. count; index ++) {UIButton * button = [UIButton buttonWithType: UIButtonTypeCustom]; button. frame = CGRectMake (buttonX, 0, [widths [index] floatValue], NAV_TAB_BAR_HEIGHT); button. titleLabel. font = TABBAR_TITLE_FONT; button. backgroundColor = [UIColor clearColor]; [button setTitle: self. myTitleArray [index] forState: UIControlStateNormal]; [button setTitleColor: [UIColor blackColor] forState: UIControlStateNormal]; [button addTarget: self action: @ selector (itemPressed :) forControlEvents: Unknown]; [self. myScrollView addSubview: button]; [_ items addObject: button]; buttonX + = [widths [index] floatValue];} if (widths. count) {[self showLineWithButtonWidth: [widths [0] floatValue];} return buttonX;}/*** @ author wujunyang, 16-01-22 13:01:33 ** @ brief select ** @ param currentIndex selected index ** @ since <# version number #> */-(void) setCurrentIndex :( NSInteger) currentIndex {_ currentIndex = currentIndex; UIButton * button = nil; button = _ items [currentIndex]; [button setTitleColor: [UIColor whiteColor] forState: UIControlStateNormal]; CGFloat offsetX = button. center. x-forwarded * 0.5; CGFloat offsetMax = _ selectedTitlesWidth-NAV_TAB_BAR_Width; if (offsetX <0 | offsetMax <0) {offsetX = 0;} else if (offsetX> offsetMax) {offsetX = offsetMax;} [self. myScrollView setContentOffset: CGPointMake (offsetX, 0) animated: YES]; [UIView animateWithDuration :. 2f animations: ^ {_ line. frame = CGRectMake (button. frame. origin. x + 2.0f, _ line. frame. origin. y, [_ itemsWidth [currentIndex] floatValue]-4.0f, _ line. frame. size. height);}];}/*** @ author wujunyang, 16-01-22 13:01:47 ** @ brief underline ** @ param width Button width ** @ since <# version number #> */-(void) showLineWithButtonWidth :( CGFloat) width {_ line = [[UIView alloc] initWithFrame: CGRectMake (2.0f, NAV_TAB_BAR_HEIGHT-3.0f, width-4.0f, 3.0f)]; _ line. backgroundColor = [UIColor blueColor]; [self. myScrollView addSubview: _ line];}-(void) cleanData {[_ items removeAllObjects]; [self. myScrollView. subviews makeObjectsPerformSelector: @ selector (removeFromSuperview)];}/*** @ author wujunyang, 16-01-22 11:01:27 ** @ brief selected event ** @ param button <# button description #> ** @ since <# version number #> */-(void) itemPressed :( UIButton *) button {NSInteger index = [_ items indexOfObject: button]; self. currentIndex = index; if ([self. delegate respondsToSelector: @ selector (itemDidSelectedWithIndex :)]) {[self. delegate itemDidSelectedWithIndex: index];} // modify the selected and unselected Button font color for (int I = 0; I <_ items. count; I ++) {if (I = index) {[button setTitleColor: [UIColor whiteColor] forState: UIControlStateNormal];} else {[_ items [I] setTitleColor: [UIColor blackColor] forState: UIControlStateNormal] ;}} [UIView animateWithDuration: 0.1 animations: ^ {button. transform = CGAffineTransformMakeScale (1.1, 1.1);} completion: ^ (BOOL finished) {[UIView animateWithDuration: 0.1 animations: ^ {button. transform = CGAffineTransformIdentity;} completion: ^ (BOOL finished) {}] ;}- (void) didreceivemorywarning {[super didreceivemorywarning]; // Dispose of any resources that can be recreated .} @ end

The code is annotated accordingly. Next we will sort it out and move it to the common MVC project framework to facilitate future project use;

If you are interested in organizing the MVC generic project framework (to save a lot of repetitive work during rapid development) You can download it, Git: https://github.com/wujunyang/MobileProject

 

Related Article

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.