iOS實戰之使用View實現導航欄下的滑動菜單

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



實現的效果如下:
當菜單個數的總長度超過一個屏寬度就計算每一個的文字寬度,若沒有則只進行一個屏平分,點擊菜單項時,滾動的視圖位置會隨著調整;下面將會把代碼貼出來;
1:控制器.h文件的內容

#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;
}

/**
 *  @brief  計算寬度
 *
 *  @param titles <#titles description#>
 *
 *  @return <#return value description#>
 */
- (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;
}
/**
 *  @brief  初始化Button
 *
 *  @param widths <#widths description#>
 *
 *  @return <#return value description#>
 */
- (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;
}

/**
 *  @brief  選中
 *
 *  @param currentIndex 選中索引
 */
- (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);
    }];
}

/**
 *  @brief  增加下劃線
 *
 *  @param width Button的寬
 */
- (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)];
}

/**
 *  @brief  選中時的事件
 *
 *  @param button <#button description#>
 */
- (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

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



使用的代碼如下:

#import "ViewController.h"

@interface ViewController ()<XBYScrollerMenuDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets=NO;
    
//    XBYScrollerMenuView *vc=[[XBYScrollerMenuView alloc]initWithFrame:CGRectMake(0, 64, 320, 50) showArrayButton:NO];
    XBYScrollerMenuView *vc=[[XBYScrollerMenuView 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

Demo

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,885評論 6 541
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,312評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 177,993評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,667評論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,410評論 6 411
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,778評論 1 328
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,775評論 3 446
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,955評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,521評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,266評論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,468評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,998評論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,696評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,095評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,385評論 1 294
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,193評論 3 398
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,431評論 2 378

推薦閱讀更多精彩內容

  • 發現 關注 消息 iOS 第三方庫、插件、知名博客總結 作者大灰狼的小綿羊哥哥關注 2017.06.26 09:4...
    肇東周閱讀 12,163評論 4 61
  • 斯里蘭卡的天氣很熱,當地人早上起很早工作,下午基本上就休息了,吃飯也很晚,中飯2-3點,晚飯8-9點。在那我跟五...
    7f2d70d15bd9閱讀 641評論 0 0
  • 寫在前面的話 前幾天,單位的同事給了楚媽幾塊鉆石戒指糖,顧名思義,就是把糖做成鉆石形狀鑲嵌在一個玩具戒指上。糖很好...
    楚媽和楚妞閱讀 732評論 0 0
  • 我祈求你是風中自由生長的精靈 如歌、如夢 在充盈的空氣里肆意流蕩 如星星點燈 如烈火燎原 在每一瞬間、每一世界 同...
    其影閱讀 221評論 0 3
  • 不二情書一直想看苦于上映時沒時間看,留給最近的自己觀看了。 該影片先從女主角的故事開始講起,那個14歲就在賭場長大...
    笑笑_feng閱讀 725評論 4 2