菜单滚动视图也是在项目开发过程中比较常用到的功能,先直接看效果图
实现的效果如下:
当菜单个数的总长度超过一个屏宽度就计算每一个的文字宽度,若没有则只进行一个屏平分,点击菜单项时,滚动的视图位置会随着调整;下面将会把代码贴出来;
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(, , 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, ); self.currentIndex=;
} /**
* @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 = ;
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 + .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 = ; 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 = ;
for (NSInteger index = ; index < widths.count; index++)
{
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(buttonX, , [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[] 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 < || offsetMax < ) {
offsetX = ;
} else if (offsetX > offsetMax){
offsetX = offsetMax;
}
[self.myScrollView setContentOffset:CGPointMake(offsetX, ) 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=; 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(, , [[UIScreen mainScreen] bounds].size.width, ) showArrayButton:YES];
vc.delegate=self;
vc.backgroundColor=[UIColor greenColor];
vc.selectedColor=[UIColor blueColor];
vc.noSlectedColor=[UIColor blackColor];
vc.myTitleArray=@[@"第一阶段",@"第二阶段",@"第三阶段",@"第四阶段",@"第五阶段"];
vc.currentIndex=;
[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 会有我的微信号,如果有问题你也可以在那找到我;当然不感兴趣无视此信息;