iOS關於菜單滾動視圖實現


菜單滾動視圖也是在項目開發過程中比較常用到的功能,先直接看效果圖

 

實現的效果如下:

當菜單個數的總長度超過一個屏寬度就計算每一個的文字寬度,若沒有則只進行一個屏平分,點擊菜單項時,滾動的視圖位置會隨着調整;下面將會把代碼貼出來;

1:控制器.h文件的內容

//
//  myScrollerViewController.h
//  testTest
//
//  Created by wujunyang on 16/1/22.
//  Copyright © 2016年 wujunyang. All rights reserved.
//

#import <UIKit/UIKit.h>

@protocol myScrollTabBarDelegate <NSObject>

@optional

- (void)itemDidSelectedWithIndex:(NSInteger)index;

@end

@interface myScrollerViewController : UIViewController

@property (nonatomic, weak) id  <myScrollTabBarDelegate>delegate;
@property (nonatomic, assign) NSInteger currentIndex;
@property(nonatomic,copy)NSArray *myTitleArray;
@end

注意:這邊創建的一個delegate,主要是為了當點擊事件時把相應的動作往外傳,並把相應的菜單索引值傳出,方便做其它操作

2:.m控制器的內容

#import "myScrollerViewController.h"

#define SCREEN_WIDTH  ([UIScreen mainScreen].bounds.size.width)
#define SCREEN_HEIGHT ([UIScreen mainScreen].bounds.size.height)
#define TABBAR_TITLE_FONT [UIFont systemFontOfSize:18.f]
#define NAV_TAB_BAR_HEIGHT 50
#define NAV_TAB_BAR_Width  SCREEN_WIDTH

@interface myScrollerViewController ()
//滾動視圖
@property(strong,nonatomic)UIScrollView *myScrollView;
//滾動下划線
@property(strong,nonatomic)UIView *line;
//所有的Button集合
@property(nonatomic,strong)NSMutableArray  *items;
//所有的Button的寬度集合
@property(nonatomic,copy)NSArray *itemsWidth;
//被選中前面的寬度合(用於計算是否進行超過一屏,沒有一屏則進行平分)
@property(nonatomic,assign)CGFloat selectedTitlesWidth;

@end

@implementation myScrollerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets=NO;
    
    self.view.backgroundColor=[UIColor whiteColor];
    
    //初始化數組
    if (!self.myTitleArray) {
        self.myTitleArray=@[@"新聞",@"NBA",@"財經",@"科技",@"軟件公司",@"健身",@"優秀文摘"];
    }
    
    self.items=[[NSMutableArray alloc]init];
    self.itemsWidth=[[NSArray alloc]init];
    
    //初始化滾動
    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];
    }
    
    //賦值跟計算滾動
    _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  計算寬度
 *
 *  @param titles <#titles description#>
 *
 *  @return <#return value description#>
 *
 *  @since <#version number#>
 */
- (NSArray *)getButtonsWidthWithTitles:(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 + 20.f;
        _selectedTitlesWidth += eachButtonWidth;
        NSNumber *width = [NSNumber numberWithFloat:eachButtonWidth];
        [widths addObject:width];
    }
    if (_selectedTitlesWidth < NAV_TAB_BAR_Width) {
        [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  初始化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:UIControlEventTouchUpInside];
        [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  選中
 *
 *  @param currentIndex 選中索引
 *
 *  @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 - NAV_TAB_BAR_Width * 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  增加下划線
 *
 *  @param width Button的寬
 *
 *  @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  選中時的事件
 *
 *  @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];
    }
    
    //修改選中跟沒選中的Button字體顏色
    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)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

代碼都有進行相應的注解,接下來會對它進行整理,把它移到通用的MVC項目框架中,方便以后項目使用;

若對整理MVC通用的項目框架(意在快速開發時省去很多重復工作)感興趣可以去下載,Git:https://github.com/wujunyang/MobileProject

 

二:編輯於2016-01-24 

在上面的代碼進行擴展,並整理上面的代碼封裝在一個插件里面實現下面的內容,可以顯示跟隱藏彈出窗,彈出窗里面顯示出每個菜單項的內容;效果如下:

使用的代碼如下:

#import "ViewController.h"

@interface ViewController ()<WJScrollerMenuDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets=NO;
    
//    WJScrollerMenuView *vc=[[WJScrollerMenuView alloc]initWithFrame:CGRectMake(0, 64, 320, 50) showArrayButton:NO];
    WJScrollerMenuView *vc=[[WJScrollerMenuView alloc]initWithFrame:CGRectMake(0, 64, [[UIScreen mainScreen] bounds].size.width, 50) showArrayButton:YES];
    vc.delegate=self;
    vc.backgroundColor=[UIColor greenColor];
    vc.selectedColor=[UIColor blueColor];
    vc.noSlectedColor=[UIColor blackColor];
    vc.myTitleArray=@[@"第一階段",@"第二階段",@"第三階段",@"第四階段",@"第五階段"];
    vc.currentIndex=0;
    [self.view addSubview:vc];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)itemDidSelectedWithIndex:(NSInteger)index
{
    NSLog(@"選中%d",index);
}

@end

插件及實例源代碼如下:http://download.csdn.net/detail/u010127054/9416365

 

 

最近有個妹子弄的一個關於擴大眼界跟內含的訂閱號,每天都會更新一些深度內容,在這里如果你感興趣也可以關注一下(嘿對美女跟知識感興趣),當然可以關注后輸入:github 會有我的微信號,如果有問題你也可以在那找到我;當然不感興趣無視此信息;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM