仿淘宝头条ios
2018-02-24 16:32:28 Aaron0619 阅读数 633

使用scrollview实现的效果:


#import "VierticalScrollView.h"
#define ViewWidth self.bounds.size.width
#define ViewHeight self.bounds.size.height
#define OrangeColor [UIColor colorWithRed:254/255.0 green:97/255.0 blue:69/255.0 alpha:1.0]
//屏幕宽度和高度
#define Screen_Width [[UIScreen mainScreen] bounds].size.width
#define Screen_Height [[UIScreen mainScreen] bounds].size.height

@interface VierticalScrollView()<UIScrollViewDelegate>
@property(nonatomic,strong) NSMutableArray *titles; //标题
@property(nonatomic,strong) NSMutableArray *types;  //类型
@property(assign, nonatomic)int index;
@property(nonatomic,strong) UIView *firstView;
@property(nonatomic,strong) UILabel *firstBtn;
@property(nonatomic,strong) UILabel *firstLabel;
@property(nonatomic,strong) UILabel *firstBtn1;
@property(nonatomic,strong) UILabel *firstLabel1;
@property(nonatomic,strong) UILabel *firstBtn2;
@property(nonatomic,strong) UILabel *firstLable2;

@property(nonatomic,strong) UIView *secondView;
@property(nonatomic,strong) UILabel *secondBtn;
@property(nonatomic,strong) UILabel *secondLabel;
@property(nonatomic,strong) UILabel *secondBtn1;
@property(nonatomic,strong) UILabel *secondLabel1;
@property(nonatomic,strong) UILabel *secondBtn2;
@property(nonatomic,strong) UILabel *secondLabel2;
@end
@implementation VierticalScrollView


-(instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        self.index = 0;
        self.delegate = self;
        
        self.firstView.frame = CGRectMake(0, 0, Screen_Width, ViewHeight);
        self.firstBtn.frame = CGRectMake(0, ViewHeight/2-9, 48, 18);
        self.firstLabel.frame = CGRectMake(CGRectGetMaxX(self.firstBtn.frame)+2, ViewHeight/2-15, Screen_Width-140, 30);
        self.firstBtn1.frame = CGRectMake(0, 12, 48, 18);
        self.firstLabel1.frame = CGRectMake(CGRectGetMaxX(self.firstBtn1.frame)+2, 10, Screen_Width-140, 20);
        self.firstBtn2.frame = CGRectMake(0, CGRectGetMaxY(self.firstBtn1.frame)+5, 48, 18);
        self.firstLable2.frame = CGRectMake(CGRectGetMaxX(self.firstBtn2.frame)+2, CGRectGetMaxY(self.firstLabel1.frame)+5, Screen_Width-140, 20);
        
        self.secondView.frame = CGRectMake(0, ViewHeight, Screen_Width, ViewHeight);
        self.secondBtn.frame = CGRectMake(0, ViewHeight/2-9, 48, 18);
        self.secondLabel.frame = CGRectMake(CGRectGetMaxX(self.secondBtn.frame)+2, ViewHeight/2-15, Screen_Width-140, 30);
        self.secondBtn1.frame = CGRectMake(0, 12, 48, 18);
        self.secondLabel1.frame = CGRectMake(CGRectGetMaxX(self.secondBtn1.frame)+2, 10, Screen_Width-140, 20);
        self.secondBtn2.frame = CGRectMake(0, CGRectGetMaxY(self.secondBtn1.frame)+5, 48, 18);
        self.secondLabel2.frame = CGRectMake(CGRectGetMaxX(self.secondBtn2.frame)+2, CGRectGetMaxY(self.secondLabel1.frame)+5, Screen_Width-140, 20);
    }
    
    return self;
}

-(void)setDataWithArray:(NSArray *)typeArray AndTitleArray:(NSArray *)titleArray{
    
    NSMutableArray *tmpArray = [NSMutableArray arrayWithCapacity:0];
    NSMutableArray<NSArray *> *finalArray = [NSMutableArray arrayWithCapacity:0];
    
    [titleArray enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [tmpArray addObject:obj];
        if ((idx +1) % 2 == 0) {
            [finalArray addObject:[NSArray arrayWithArray:tmpArray]];
            [tmpArray removeAllObjects];
        } else {
            if (idx == (titleArray.count - 1)) {
                [finalArray addObject:[NSArray arrayWithArray:tmpArray]];
                [tmpArray removeAllObjects];
            }
        }
    }];
    
    NSMutableArray *tmpArray2 = [NSMutableArray arrayWithCapacity:0];
    NSMutableArray<NSArray *> *finalArray2 = [NSMutableArray arrayWithCapacity:0];
    
    [typeArray enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [tmpArray2 addObject:obj];
        if ((idx +1) % 2 == 0) {
            [finalArray2 addObject:[NSArray arrayWithArray:tmpArray2]];
            [tmpArray2 removeAllObjects];
        } else {
            if (idx == (typeArray.count - 1)) {
                [finalArray2 addObject:[NSArray arrayWithArray:tmpArray2]];
                [tmpArray2 removeAllObjects];
            }
        }
    }];
    self.types = [NSMutableArray arrayWithArray:finalArray2];
    self.titles = [NSMutableArray arrayWithArray:finalArray];
    [self setDataWithIndex:self.index];
    [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(nextView) userInfo:nil repeats:YES];
}

- (void)setDataWithIndex:(int)index{
    NSArray *array = self.titles[index];
    NSArray *typeArray = self.types[index];
    //根据单双数设置单行和双行Label的显示和隐藏
    if (array.count==1) {
        self.firstLabel.text = array[0];
        self.firstLabel.hidden = NO;
        self.firstLabel1.hidden = YES;
        self.firstLable2.hidden = YES;
    }else{
        self.firstLabel1.text = array[0];
        self.firstLable2.text = array[1];
        self.firstLabel1.hidden = NO;
        self.firstLable2.hidden = NO;
        self.firstLabel.hidden = YES;
    }
    if (typeArray.count == 1) {
        self.firstBtn.text = typeArray[0];
        self.firstBtn.hidden = NO;
        self.firstBtn1.hidden = YES;
        self.firstBtn2.hidden = YES;
    }else{
        self.firstBtn1.text = typeArray[0];
        self.firstBtn2.text = typeArray[1];
        self.firstBtn1.hidden = NO;
        self.firstBtn2.hidden = NO;
        self.firstBtn.hidden = YES;
    }
    NSArray *nextArray = nil;
    NSArray *nextTypeArray = nil;          //数组循环
    if (index==self.titles.count-1) {
        nextArray = self.titles[0];
    }else{
        nextArray = self.titles[index+1];
    }
    if (index==self.types.count-1) {
        nextTypeArray = self.types[0];
    }else{
        nextTypeArray = self.types[index+1];
    }
    if (nextArray.count==1) {
        self.secondLabel.text = nextArray[0];
        self.secondLabel.hidden = NO;
        self.secondLabel1.hidden = YES;
        self.secondLabel2.hidden = YES;
    }else{
        self.secondLabel1.text = nextArray[0];
        self.secondLabel2.text = nextArray[1];
        self.secondLabel1.hidden = NO;
        self.secondLabel2.hidden = NO;
        self.secondLabel.hidden = YES;
    }
    if (nextTypeArray.count==1) {
        self.secondBtn.text = nextTypeArray[0];
        self.secondBtn.hidden = NO;
        self.secondBtn1.hidden = YES;
        self.secondBtn2.hidden = YES;
    }else{
        self.secondBtn1.text = nextTypeArray[0];
        self.secondBtn2.text = nextTypeArray[1];
        self.secondBtn1.hidden = NO;
        self.secondBtn2.hidden = NO;
        self.secondBtn.hidden = YES;
    }
}

-(void)nextView{
    [self setContentOffset:CGPointMake(0, ViewHeight) animated:YES];
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView.contentOffset.y==ViewHeight) {
        
        if (self.index == self.titles.count-1) {
            self.index = 0;
        }else{
            self.index++;
        }
        [self setDataWithIndex:self.index];
        [scrollView setContentOffset:CGPointMake(0, 0) animated:NO];
    }
    
}

- (UIView *)firstView
{
    if (!_firstView) {
        _firstView = [[UIView alloc] init];
        _firstView.backgroundColor = [UIColor whiteColor];
        [self addSubview:_firstView];
        [self.firstView addSubview:self.firstBtn];
        [self.firstView addSubview:self.firstLabel];
        [self.firstView addSubview:self.firstBtn1];
        [self.firstView addSubview:self.firstLabel1];
        [self.firstView addSubview:self.firstBtn2];
        [self.firstView addSubview:self.firstLable2];
    }
    return _firstView;
}

- (UILabel *)firstBtn
{
    if (!_firstBtn) {
        _firstBtn = [[UILabel alloc] init];
        _firstBtn.textAlignment = NSTextAlignmentCenter;
        _firstBtn.layer.borderWidth = 1.0;
        _firstBtn.layer.borderColor = OrangeColor.CGColor;
        _firstBtn.font = [UIFont systemFontOfSize:11];
        _firstBtn.layer.cornerRadius = 3.0;
        _firstBtn.textColor = OrangeColor;
    }
    return _firstBtn;
}

- (UILabel *)firstLabel
{
    if (!_firstLabel) {
        _firstLabel = [[UILabel alloc] init];
        _firstLabel.font = [UIFont systemFontOfSize:13.0];
        _firstLabel.textColor = [UIColor darkGrayColor];
    }
    return _firstLabel;
}

- (UILabel *)firstBtn1
{
    if (!_firstBtn1) {
        _firstBtn1 = [[UILabel alloc] init];
        _firstBtn1.layer.borderWidth = 1.0;
        _firstBtn1.textAlignment = NSTextAlignmentCenter;
        _firstBtn1.layer.borderColor = OrangeColor.CGColor;
        _firstBtn1.font = [UIFont systemFontOfSize:11];
        _firstBtn1.layer.cornerRadius = 3.0;
        _firstBtn1.textColor = OrangeColor;
    }
    return _firstBtn1;
}

- (UILabel *)firstLabel1
{
    if (!_firstLabel1) {
        _firstLabel1 = [[UILabel alloc] init];
        _firstLabel1.font = [UIFont systemFontOfSize:13.0];
        _firstLabel1.textColor = [UIColor darkGrayColor];
    }
    return _firstLabel1;
}

- (UILabel *)firstBtn2
{
    if (!_firstBtn2) {
        _firstBtn2 = [[UILabel alloc] init];
        _firstBtn2.layer.borderWidth = 1.0;
        _firstBtn2.layer.borderColor = OrangeColor.CGColor;
        _firstBtn2.font = [UIFont systemFontOfSize:11];
        _firstBtn2.textAlignment = NSTextAlignmentCenter;
        _firstBtn2.layer.cornerRadius = 3.0;
        _firstBtn2.textColor = OrangeColor;
    }
    return _firstBtn2;
}

- (UILabel *)firstLable2
{
    if (!_firstLable2) {
        _firstLable2 = [[UILabel alloc] init];
        _firstLable2.font = [UIFont systemFontOfSize:13.0];
        _firstLable2.textColor = [UIColor darkGrayColor];
    }
    return _firstLable2;
}

- (UIView *)secondView
{
    if (!_secondView) {
        _secondView = [[UIView alloc] init];
        _secondView.backgroundColor = [UIColor whiteColor];
        [self addSubview:_secondView];
        [self.secondView addSubview:self.secondBtn];
        [self.secondView addSubview:self.secondLabel];
        [self.secondView addSubview:self.secondBtn1];
        [self.secondView addSubview:self.secondLabel1];
        [self.secondView addSubview:self.secondBtn2];
        [self.secondView addSubview:self.secondLabel2];
    }
    return _secondView;
}

- (UILabel *)secondBtn
{
    if (!_secondBtn) {
        _secondBtn = [[UILabel alloc] init];
        _secondBtn.layer.borderWidth = 1.0;
        _secondBtn.layer.borderColor = [UIColor redColor].CGColor;
        _secondBtn.font = [UIFont systemFontOfSize:11];
        _secondBtn.textAlignment = NSTextAlignmentCenter;
        _secondBtn.layer.cornerRadius = 3.0;
        _secondBtn.textColor =[UIColor redColor];
    }
    return _secondBtn;
}

- (UILabel *)secondLabel
{
    if (!_secondLabel) {
        _secondLabel = [[UILabel alloc] init];
        _secondLabel.font = [UIFont systemFontOfSize:13.0];
        _secondLabel.textColor = [UIColor darkGrayColor];
    }
    return _secondLabel;
}

- (UILabel *)secondBtn1
{
    if (!_secondBtn1) {
        _secondBtn1 = [[UILabel alloc] init];
        _secondBtn1.layer.borderWidth = 1.0;
        _secondBtn1.layer.borderColor = [UIColor redColor].CGColor;
        _secondBtn1.font = [UIFont systemFontOfSize:11];
        _secondBtn1.layer.cornerRadius = 3.0;
        _secondBtn1.textAlignment = NSTextAlignmentCenter;
        _secondBtn1.textColor = [UIColor redColor];
    }
    return _secondBtn1;
}

- (UILabel *)secondLabel1
{
    if (!_secondLabel1) {
        _secondLabel1 = [[UILabel alloc] init];
        _secondLabel1.font = [UIFont systemFontOfSize:13.0];
        _secondLabel1.textColor = [UIColor darkGrayColor];
    }
    return _secondLabel1;
}

- (UILabel *)secondBtn2
{
    if (!_secondBtn2) {
        _secondBtn2 = [[UILabel alloc] init];
        _secondBtn2.layer.borderWidth = 1.0;
        _secondBtn2.layer.borderColor = [UIColor redColor].CGColor;
        _secondBtn2.font = [UIFont systemFontOfSize:11];
        _secondBtn2.layer.cornerRadius = 3.0;
        _secondBtn2.textAlignment = NSTextAlignmentCenter;
        _secondBtn2.textColor = [UIColor redColor];
    }
    return _secondBtn2;
}

- (UILabel *)secondLabel2
{
    if (!_secondLabel2) {
        _secondLabel2 = [[UILabel alloc] init];
        _secondLabel2.font = [UIFont systemFontOfSize:13.0];
        _secondLabel2.textColor = [UIColor darkGrayColor];
    }
    return _secondLabel2;
}

使用方法:

NSArray *dataTypeArray = @[@"类型1",@"类型2",@"类型3",@"类型4",@"类型5"];
NSArray *dataTitleArray = @[@"默认标题1",@"默认标题2",@"默认标题3",@"默认标题4",@"默认标题5"];
VierticalScrollView *rollView = [[VierticalScrollView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(imageV.frame), 100, self.view.frame.size.width, 60)];
[rollView setDataWithArray:dataTypeArray AndTitleArray:dataTitleArray];
[self.view addSubview:rollView];

GitHub地址

2017-09-21 20:41:00 weixin_34054866 阅读数 22

pch文件

6348860-444fc2147feb8582.png
屏幕快照 2017-09-21 下午8.47.55.png
#ifndef my_pch
#define my_pch

// Include any system framework and library headers here that should be included in all compilation units.
// You will also need to set the Prefix Header build setting of one or more of your targets to reference this file.
//用于适配的宏
#define  SCR_W  [UIScreen mainScreen].bounds.size.width    // 屏幕宽度
#define  SCR_H  [UIScreen mainScreen].bounds.size.height   // 屏幕高度

#define  FIT_X(x)  (SCR_W/375.*(x))     // 用于x轴适配
#define  FIT_Y(y)  (SCR_H/667.*(y))     // 用于y轴适配
#endif /* my_pch */

6348860-25ae415396b9e4dd.png
屏幕快照 2017-09-21 下午8.48.30.png

注:NewsCollectionViewCell 继承于 UICollectionViewCell

AppDelegate.m

#import "ViewController.h"
@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    ViewController *vc = [[ViewController alloc]init];
    
    UINavigationController *navVc = [[UINavigationController alloc]initWithRootViewController:vc];
    self.window.rootViewController = navVc;
    return YES;
}

ViewController.m

#import "ViewController.h"
#import "NewsCollectionViewCell.h"
#define BTN_W FIT_X(80) // 每个标题按钮的宽度
@interface ViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UITableViewDelegate,UITableViewDataSource>
{
    NSArray *_allTitles; //所有的新闻标题
    NSArray *_allDatas; //说有的新闻数据
    NSArray *_tableDatas; //给每一个网格单元格中的表格视图加载数据的数组
    
}

@property (nonatomic,strong)UIScrollView *titleScrView;//标题滚动视图
@property (nonatomic,strong)UILabel *titleIndicateLable; //标题下方的指示标签
@property (nonatomic,strong)UICollectionView *contentsColView; //新闻内容网格视图
@end

@implementation ViewController

#pragma mark - 懒加载控件

//标题滚动视图
- (UIScrollView *)titleScrView
{
    if (!_titleScrView)
    {
        _titleScrView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, FIT_Y(64), SCR_W, FIT_Y(44))];
        _titleScrView.contentSize = CGSizeMake(BTN_W * _allTitles.count, FIT_Y(44));
        _titleScrView.showsHorizontalScrollIndicator = NO;
        
        for (int i = 0 ; i < _allTitles.count; i++)
        {
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            btn.frame = CGRectMake(i*BTN_W, 0, BTN_W, FIT_Y(44));
            [btn setTitle:_allTitles[i] forState:UIControlStateNormal];
            [btn setTitle:_allTitles[i] forState:UIControlStateSelected];
            [btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
            if (i == 0) {
                btn.selected = YES;
            }
            btn.tag = i+100;
            [btn addTarget:self action:@selector(titleBtnHandle:) forControlEvents:UIControlEventTouchUpInside];
            [_titleScrView addSubview:btn];
        }
        [_titleScrView addSubview:self.titleIndicateLable];
        
    }
    return _titleScrView;
}

//标题指示标签
- (UILabel *)titleIndicateLable
{
    if (!_titleIndicateLable)
    {
        _titleIndicateLable = [[UILabel alloc]initWithFrame:CGRectMake(0, FIT_Y(44), BTN_W, FIT_Y(2))];
        _titleIndicateLable.backgroundColor = [UIColor redColor];
    }
    return _titleIndicateLable;
}
//新闻内容视图
- (UICollectionView *)contentsColView
{
    if (!_contentsColView)
    {
        //实例化网格布局对象
        UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc]init];
        //设置每个单元格大小
        flow.itemSize = CGSizeMake(SCR_W, SCR_H-FIT_Y(44));
        //设置最小行间距
        flow.minimumLineSpacing = 0;
        //设置最小列间距
        flow.minimumInteritemSpacing = 0;
        //设置滚动方向水平滚动
        flow.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        
        
        //实例化网格视图
        _contentsColView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, FIT_Y(110), SCR_W, SCR_H-FIT_Y(44)) collectionViewLayout:flow];
        _contentsColView.tag = 444;
        _contentsColView.dataSource = self;
        _contentsColView.delegate = self;
        _contentsColView.pagingEnabled = YES; //分页滚动
        //注册一个cell
        [_contentsColView registerClass:[NewsCollectionViewCell class] forCellWithReuseIdentifier:@"NewsCell"];
        
    }
    return _contentsColView;
}
//标题滚动button方法
- (void)titleBtnHandle:(UIButton *)btn
{
    
    //点击按钮让collection滚动
    [self.contentsColView scrollRectToVisible:CGRectMake((btn.tag-100)*SCR_W, 0, SCR_W, FIT_Y(44)) animated:YES];
}
#pragma mark - UICollectionViewDataSource
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _allTitles.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"NewsCell";
    NewsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    if (!cell)
    {
        cell = [[NewsCollectionViewCell alloc]initWithFrame:CGRectMake(0, 0, SCR_W, SCR_H-FIT_Y(44))];
    }
    cell.newsTable.dataSource = self;
    cell.newsTable.delegate = self;
    return cell;
}
#pragma mark - UICollectionViewDelegate
//将要出现cell时回调的方法
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //如果内容网格视图滚动,执行if中的代码
    if (scrollView.tag == 444)
    {
        int index = scrollView.contentOffset.x / SCR_W;
        //其他的button变为normal颜色
        for (int i = 0; i < _allTitles.count ; i++)
        {
            UIButton *btn = (UIButton *)[self.titleScrView viewWithTag:i+100];
            btn.selected = NO;
            if (index == i)
            {
                btn.selected = YES;
            }
        }
        //移动指示标签
        [UIView animateWithDuration:0.185 animations:^{
            
            self.titleIndicateLable.frame = CGRectMake(index * BTN_W, FIT_Y(42), BTN_W, FIT_Y(2));
            
        }];
        
        //让标题滚动视图滚动到指定位置
        [self.titleScrView scrollRectToVisible:CGRectMake(BTN_W*index, 0, BTN_W, FIT_Y(44)) animated:YES];
        
    }
}
//即将滚动出现cell时的回调方法
-(void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"%ld",indexPath.row);
    //改变网格单元格中表格视图的内容
    _tableDatas = _allDatas[indexPath.row];
    NewsCollectionViewCell *newsCell = (NewsCollectionViewCell *)cell;
    [newsCell.newsTable reloadData];
    
    
}
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _tableDatas.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        
    }
    
    cell.textLabel.text = _tableDatas[indexPath.row];
    return cell;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    _allTitles = @[@"头条",@"新闻",@"体育",@"科技",@"财经",@"军事",@"娱乐",@"家居",@"健康",@"游戏"];
    _allDatas = @[@[@"头条1",@"头条2",@"头条3"],
                  @[@"新闻1",@"新闻2",@"新闻3"],
                  @[@"体育1",@"体育2",@"体育3"],
                  @[@"科技1",@"科技2",@"科技3"],
                  @[@"财经1",@"财经2",@"财经3"],
                  @[@"军事1",@"军事2",@"军事3"],
                  @[@"娱乐1",@"娱乐2",@"娱乐3"],
                  @[@"家居1",@"家居2",@"家居3"],
                  @[@"健康1"],
                  @[@"Game1",@"Game2"]
                  ];
    
    _tableDatas = _allDatas[0];
    
    UIView *v  = [[UIView alloc]init];
    [self.view addSubview: v];
    
    [self.view addSubview:self.titleScrView];
    [self.view addSubview:self.contentsColView];
    
    
    
}



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

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end

NewsCollectionViewCell.h

@interface NewsCollectionViewCell : UICollectionViewCell
@property (nonatomic,strong)UITableView *newsTable;
@end

NewsCollectionViewCell.m

#import "NewsCollectionViewCell.h"

@implementation NewsCollectionViewCell
#pragma Mark - 重写
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.newsTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCR_W, SCR_H-FIT_Y(44)) style:UITableViewStylePlain];
        [self.contentView addSubview:self.newsTable];
    }
    return self;
}

@end
2018-09-25 09:20:00 weixin_33909059 阅读数 24

最近两个项目都用到类似淘宝头条的功能,就是文字上下无限循环滚动,所以决定简单封装一下,以便以后使用。由于习惯用SDCycleScrollView来做广告图的无限循环滚动,所以这里文字无限滚动的核心是源于此。

效果如下:


1055266-d0cf45b80158e821.gif
demo效果

考虑到这种滚动需求样式的多变性,这里的封装还是基于 UICollectionView,提供上下和左右滚动两种方式,而且基于UICollectionView的复用特性,性能也是不错的。如果样式不一样,直接替换FHCTopLineCollectionViewCell为你自定义的cell即可。

FHCTopLineViewDelegate提供了两个代理方法

/**
 点击滚动文字回调
 @param topLine FHCTopLineView
 @param index 选中文字的index
 */
- (void)topLineView:(FHCTopLineView *)topLine didSelectItemAtIndex:(NSInteger)index;


/**
 文字滚动的回调
 @param topLine FHCTopLineView
 @param index 滚动到的位置index
 */
- (void)topLineView:(FHCTopLineView *)topLine didScrollToIndex:(NSInteger)index;

平时用习惯了,所以控制滚动的属性也是参照SDCycleScrollView

///////////////////////////  滚动控制接口 ///////////////////////////////

/** 自动滚动间隔时间,默认2s */
@property (nonatomic, assign) CGFloat autoScrollTimeInterval;

/** 是否无限循环,默认Yes */
@property (nonatomic,assign) BOOL infiniteLoop;

/** 是否自动滚动,默认Yes */
@property (nonatomic,assign) BOOL autoScroll;

/** 是否允许用户拖动,默认Yes */
@property (nonatomic, assign) BOOL enableDrag;

/** 文字滚动方向,默认为垂直滚动 */
@property (nonatomic, assign) UICollectionViewScrollDirection scrollDirection;

/** 代理 */
@property (nonatomic, weak) id<FHCTopLineViewDelegate> delegate;

///////////////////////////// 数据源接口 ////////////////////////////////////

/** 数据源数组 */
@property (nonatomic, strong) NSArray *titlesGroup;

Demo地址:FHCTopLineView

2018-05-17 16:32:00 weixin_33958585 阅读数 37

日常记录工程中(公司产品日常抄淘宝)遇到的问题~~
线上效果图(原谅我没有GIF的图):

3134378-9bf9212e1cdbbbc9.png
Tabbar效果图1

3134378-457695a9d6b89f91.png
Tabbar效果图2

解释说明:第一个tabbar点击时“鸡头”顺时针旋转一圈,其余tabbar点击时抖动效果(真的是仿淘宝的)……
→ 好了开始上代码↓:
创建自定义的 SLMainTabbarVc

//SLMainTabbarVC.h 文件
#import <UIKit/UIKit.h>
#import "SLTabBarViewController.h"
@interface SLMainTabbarVC : SLTabBarViewController
@end

//-------------------------------

//SLMainTabbarVC.m 文件
#import "SLMainTabbarVC.h"
#import "ViewController.h"

@implementation SLMainTabbarVC
-(instancetype)init{
    if (self = [super init]) {
        [self createUI];
        self.delegate = self;
    }
    return self;
}

-(void)createUI{
    ViewController *vc1 = [[ViewController alloc] init];
    vc1.hidesBottomBarWhenPushed = NO;
    UINavigationController *nav1 = [[UINavigationController alloc] initWithRootViewController:vc1];
    
    ViewController *vc2 = [[ViewController alloc] init];
    vc2.hidesBottomBarWhenPushed = NO;
    UINavigationController *nav2 = [[UINavigationController alloc] initWithRootViewController:vc2];
    
    ViewController *vc3 = [[ViewController alloc] init];
    vc3.hidesBottomBarWhenPushed = NO;
    UINavigationController *nav3 = [[UINavigationController alloc] initWithRootViewController:vc3];
    
    ViewController *vc4 = [[ViewController alloc] init];
    vc4.hidesBottomBarWhenPushed = NO;
    UINavigationController *nav4 = [[UINavigationController alloc] initWithRootViewController:vc4];
    
    ViewController *vc5 = [[ViewController alloc] init];
    vc5.hidesBottomBarWhenPushed = NO;
    UINavigationController *nav5 = [[UINavigationController alloc] initWithRootViewController:vc5];
    
    NSArray *vc = @[nav1,nav2,nav3,nav4,nav5];
    NSArray *title = @[@"首页",@"分类",@"发现中心",@"购物车",@"个人中心"]; 
    NSArray *image = @[@"tab_1_n-",@"tab_2_n-",@"tab_3_n-",@"tab_4_n-",@"tab_5_n-"];
    NSArray *selectImage = @[@"tab_1_h-",@"tab_2_h-",@"tab_3_h-",@"tab_4_h-",@"tab_5_h-"];
    
    for (int i = 0; i<vc.count; i++) {
        [self addChildViewController:vc[i] andTitle:title[i] image:image[i] selectImage:selectImage[i]];
    }

}

-(void)addChildViewController:(UIViewController *)vc andTitle:(NSString *)title image:(NSString *)image selectImage:(NSString *)selectImage{
    //设置title和图片
    //**特别说明**:见代码后面
    vc.tabBarItem.title = @"";
    vc.tabBarItem.image = [[UIImage imageNamed:image]imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)];
    vc.tabBarItem.selectedImage = [[UIImage imageNamed:selectImage] imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)];
    
//    //设置文字位置,在有文字时用于调整文字的位置
//    [vc.tabBarItem setTitlePositionAdjustment:UIOffsetMake(0, -2.5)];
    //设置图片位置  注意:图片 上下 or 左右 的间距要一样,否侧有些手机上会变形
    [vc.tabBarItem setImageInsets:UIEdgeInsetsMake(7, 0, -7, 0)]; //
    
    //添加到
     [self addChildViewController:vc];
}

#pragma mark - UITabBarControllerDelegate
//点击下面的tabBar的按钮时候,根据BOOL值来判断是否处于可继续点击状态
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController NS_AVAILABLE_IOS(3_0){
    //此方法里我用来判断在用户点击“个人中心”时是否登录
    return YES;
}

//此方法系统自动调用,写在继承自UITabBarController的controller中
//设置点击的动画----本次重点
-(void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item{
    NSInteger index = [self.tabBar.items indexOfObject:item];
    NSMutableArray * tabbarbuttonArray = [NSMutableArray array];
    for (UIView *tabBarButton in self.tabBar.subviews) {
        if ([tabBarButton isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
            [tabbarbuttonArray addObject:tabBarButton];
        }
    }
    
    if (index == 0) { //顺时针旋转效果
        CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
        animation.duration = 0.3;
        //如果这里想设置成一直自旋转,可以设置为MAXFLOAT,否则设置具体的数值则代表执行多少次
        animation.repeatCount = 1;
        animation.autoreverses = NO;
        //默认是顺时针效果,若将fromValue和toValue的值互换,则为逆时针效果
        animation.fromValue = [NSNumber numberWithFloat:0.f];
        animation.toValue = [NSNumber numberWithFloat: M_PI *2];
        [[tabbarbuttonArray[index] layer] addAnimation:animation forKey:nil];
        
    }else{ //抖动效果
        CABasicAnimation*pulse = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
        pulse.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        pulse.duration = 0.1;
        pulse.repeatCount = 1;
        pulse.autoreverses = YES;
        pulse.fromValue = [NSNumber numberWithFloat:0.7];
        pulse.toValue = [NSNumber numberWithFloat:1.3];
        [[tabbarbuttonArray[index] layer] addAnimation:pulse forKey:nil];
    }
   
}

//-------------------------------

//在AppDelegate里跟系统的一样使用
    SLMainTabbarVC *tabbar = [[SLMainTabbarVC alloc] init];
    _tabBarVC = tabbar;
    self.window.rootViewController = tabbar;


特别说明
→1、由于第一个tabbar的“鸡头”不能显示“首页”文字,所以我这里的tabbar没有文字,都是image和title在一起的图片,但是要注意,此时的NavigationController的RootViewController的导航文字不要这样 vc.title = @"首页";设置,因为这是tabbar的item.title在当前VC显示时对应的tabbar还是会显示 vc.title 的文字。
如果vc的title必须设置,可以用下面方法代替:

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    UILabel *label = [UILabel new];
    label.frame = CGRectMake(0, 0, 100, 40); //防止有些版本手机不显示title的情况,设置一个frame
    label.textAlignment = NSTextAlignmentCenter;
    label.text = @"发现";  
    label.textColor = [UIColor blackColor];
    label.font = [UIFont systemFontOfSize:17];
    self.navigationItem.titleView = label;
}

→2、item.image和item.image分开的情况时的做法跟现在的一样样,在设置addChildViewController方法里 vc.tabBarItem.title = titie; 就可以了。此时的情况本宝宝只试过抖动的效果,别的效果没有试过,同学们可以试着玩玩,指不定就玩出了别的花样O(∩_∩)O~


对于tabar的一些延伸
1、tabBarItem的image&title的改变
要求:在用户登录成功后换掉第2个tabBarItem的image,在SLMainTabbarVC.m 文件里接受通知:

//登录成功后通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(theLogin) name:LoginSuccessfullNoticetion object:nil];
//方法
-(void)theLogin{
    UITabBarItem *item = [self.tabBar.items objectAtIndex:1];
    item.image = [[UIImage imageNamed:@"tab_2_d_n-"]imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)];
    item.selectedImage = [[UIImage imageNamed:@"tab_2_d_h-"] imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)];
}

//代理方法里
-(void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item{
    NSInteger index = [self.tabBar.items indexOfObject:item];
    NSMutableArray * tabbarbuttonArray = [NSMutableArray array];
    for (UIView *tabBarButton in self.tabBar.subviews) {
        if ([tabBarButton isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
            [tabbarbuttonArray addObject:tabBarButton];
        }
    }
    
    //item修改了图片之后,会影响subviews的顺序。
    //修改了第二个的图片,会导致第二个UITabBarButton在subviews变到最后一个,所以根据位置重新排下序
    tabbarbuttonArray = [tabbarbuttonArray sortedArrayUsingComparator:^NSComparisonResult(UIView *obj1, UIView *obj2) {
        NSComparisonResult result = [[NSNumber numberWithFloat:obj1.frame.origin.x] compare:[NSNumber numberWithFloat:obj2.frame.origin.x]];
        return result;
    }];

    //后面内容和上面一样

}

2013-09-03 11:11:28 smk524198002 阅读数 4100


iOS 自带的TabBar样式比较单一,很多时候需要自定义,仿淘宝的效果如下:

自定义TabBar的类MainController继承UITabBarController

#import <UIKit/UIKit.h>



@interface MainController : UITabBarController
{
    @private
    UIButton *homeBtn;
    UIButton *myTaobaoBtn;
    UIButton *cartBtn;
    UIButton *weitaoBtn;
    UIButton *searchBtn;
    
    UIImageView *tabbarBG;
    UIImageView *itemBG;
    

}

- (void)createCustomTabBar; //创建自定义TabBar
- (void)showTabBar; //显示TabBar
- (void)hideTabBar; //隐藏TabBar

@end



主要是上面三个方法:

createCustomTabBar创建一个自定义TabBar,主要思想就是:把系统自带的TabBar隐藏,然后在TabBar的位置上放自定义的TabBar视图

自定义TabBar的视图层次关系:

背景(最下面),选择图片(中间),按钮(最上面)

主要代码:

- (void)createCustomTabBar
{
    /*
     *层次关系:背景(最下面),选择图片(中间),按钮(最上面)
     */
    
    tabbarBG = [[UIImageView alloc]initWithFrame:CGRectMake(0, 480-49, 320, 49)];
    tabbarBG.image = [UIImage imageNamed:@"tabbar_background.png"];
    tabbarBG.userInteractionEnabled = YES;
    [self.view addSubview:tabbarBG];
    
    
    itemBG = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"tabbar_item_selected.png"]];
    [tabbarBG addSubview:itemBG];
    
    homeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    homeBtn.tag = 0;
    homeBtn.frame = CGRectMake(0.0, 0.0, 64.0, 49.0);
    [homeBtn setImage:[UIImage imageNamed:@"tabbar_home_unselected.png"] forState:UIControlStateNormal];
    [homeBtn setImage:[UIImage imageNamed:@"tabbar_home_selected.png"] forState:UIControlStateSelected];
    [homeBtn setTitle:@"首页" forState:UIControlStateNormal];
    [homeBtn setTitleColor:[UIColor colorWithRed:135.0/255.0 green:145.0/255.0 blue:165.0/255.0 alpha:1] forState:UIControlStateNormal];
    [homeBtn setTitleColor:[UIColor colorWithRed:235.0/255.0 green:81.0/255.0 blue:17.0/255.0 alpha:1] forState:UIControlStateSelected];
    homeBtn.titleLabel.font = [UIFont systemFontOfSize:10.0];
    [homeBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -29, -30, 0)];
    [homeBtn setImageEdgeInsets:UIEdgeInsetsMake(-10, 18, 0, 18)];
    [homeBtn addTarget:self action:@selector(homeBtn_Click:) forControlEvents:UIControlEventTouchUpInside];
    homeBtn.selected = YES;
    itemBG.frame = CGRectMake(0, 0, 64, 49);
    [tabbarBG addSubview:homeBtn];
    
    
     myTaobaoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    myTaobaoBtn.tag = 1;
    myTaobaoBtn.frame = CGRectMake(64, 0.0, 64.0, 49.0);
    [myTaobaoBtn setImage:[UIImage imageNamed:@"tabbar_mytaobao_unselected.png"] forState:UIControlStateNormal];
    [myTaobaoBtn setImage:[UIImage imageNamed:@"tabbar_mytaobao_selected.png"] forState:UIControlStateSelected];
    [myTaobaoBtn setTitle:@"我的淘宝" forState:UIControlStateNormal];
    [myTaobaoBtn setTitleColor:[UIColor colorWithRed:135.0/255.0 green:145.0/255.0 blue:165.0/255.0 alpha:1] forState:UIControlStateNormal];
    [myTaobaoBtn setTitleColor:[UIColor colorWithRed:235.0/255.0 green:81.0/255.0 blue:17.0/255.0 alpha:1] forState:UIControlStateSelected];
    myTaobaoBtn.titleLabel.font = [UIFont systemFontOfSize:10.0];
    [myTaobaoBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -29, -30, 0)];
    [myTaobaoBtn setImageEdgeInsets:UIEdgeInsetsMake(-10, 18, 0, 18)];
    [myTaobaoBtn addTarget:self action:@selector(myTaobaoBtn_Click:) forControlEvents:UIControlEventTouchUpInside];
    [tabbarBG addSubview:myTaobaoBtn];
    
  
    cartBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    cartBtn.tag = 2;
    cartBtn.frame = CGRectMake(64*2, 0.0, 64.0, 49.0);
    [cartBtn setImage:[UIImage imageNamed:@"tabbar_cart_unselected.png"] forState:UIControlStateNormal];
    [cartBtn setImage:[UIImage imageNamed:@"tabbar_cart_selected.png"] forState:UIControlStateSelected];
    [cartBtn setTitle:@"购物车" forState:UIControlStateNormal];
    [cartBtn setTitleColor:[UIColor colorWithRed:135.0/255.0 green:145.0/255.0 blue:165.0/255.0 alpha:1] forState:UIControlStateNormal];
    [cartBtn setTitleColor:[UIColor colorWithRed:235.0/255.0 green:81.0/255.0 blue:17.0/255.0 alpha:1] forState:UIControlStateSelected];
    cartBtn.titleLabel.font = [UIFont systemFontOfSize:10.0];
    [cartBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -27, -30, 0)];
    [cartBtn setImageEdgeInsets:UIEdgeInsetsMake(-10, 18, 0, 18)];
    [cartBtn addTarget: self action:@selector(cartBtn_Click:) forControlEvents:UIControlEventTouchUpInside];
    [tabbarBG addSubview:cartBtn];
    
    weitaoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    weitaoBtn.tag = 3;
    weitaoBtn.frame = CGRectMake(64*3, 0.0, 64.0, 49.0);
    [weitaoBtn setImage:[UIImage imageNamed:@"tabbar_weitao_unselected.png"] forState:UIControlStateNormal];
    [weitaoBtn setImage:[UIImage imageNamed:@"tabbar_weitao_selected.png"] forState:UIControlStateSelected];
    [weitaoBtn setTitle:@"微淘" forState:UIControlStateNormal];
    [weitaoBtn setTitleColor:[UIColor colorWithRed:135.0/255.0 green:145.0/255.0 blue:165.0/255.0 alpha:1] forState:UIControlStateNormal];
    [weitaoBtn setTitleColor:[UIColor colorWithRed:235.0/255.0 green:81.0/255.0 blue:17.0/255.0 alpha:1] forState:UIControlStateSelected];
    weitaoBtn.titleLabel.font = [UIFont systemFontOfSize:10.0];
    [weitaoBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -27, -30, 0)];
    [weitaoBtn setImageEdgeInsets:UIEdgeInsetsMake(-10, 18, 0, 18)];
    
    [weitaoBtn addTarget: self action:@selector(weitaoBtn_Click:) forControlEvents:UIControlEventTouchUpInside];
    [tabbarBG addSubview:weitaoBtn];
    
    
    searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    searchBtn.tag = 4;
    searchBtn.frame = CGRectMake(64*4, 0.0, 64.0, 49.0);
    [searchBtn setImage:[UIImage imageNamed:@"tabbar_search_unselected.png"] forState:UIControlStateNormal];
    [searchBtn setImage:[UIImage imageNamed:@"tabbar_search_selected.png"] forState:UIControlStateSelected];
    [searchBtn setTitle:@"搜索" forState:UIControlStateNormal];
    [searchBtn setTitleColor:[UIColor colorWithRed:135.0/255.0 green:145.0/255.0 blue:165.0/255.0 alpha:1] forState:UIControlStateNormal];
    [searchBtn setTitleColor:[UIColor colorWithRed:235.0/255.0 green:81.0/255.0 blue:17.0/255.0 alpha:1] forState:UIControlStateSelected];
    searchBtn.titleLabel.font = [UIFont systemFontOfSize:10.0];
    [searchBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -27, -30, 0)];
    [searchBtn setImageEdgeInsets:UIEdgeInsetsMake(-10, 18, 0, 18)];
    
    [searchBtn addTarget: self action:@selector(searchBtn_Click:) forControlEvents:UIControlEventTouchUpInside];
    [tabbarBG addSubview:searchBtn];
}


然后在跳转的时候,有时候需要隐藏TabBar,返回到控制页面的时候需要显示TabBar,下面是show和hide方法

- (void)showTabBar
{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.35];
    tabbarBG.frame = CGRectMake(0, 431, 320, 49);
    [UIView commitAnimations];
     NSLog(@"显示TabBar");
}
- (void)hideTabBar
{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.35];
    tabbarBG.frame = CGRectMake(-320, 431, 320, 49);
    [UIView commitAnimations];
    NSLog(@"隐藏TabBar");
}


这里加了动画,隐藏了系统自带的TabBar之后,那一块会变成黑色,因为被自定义的TabBar隐藏,所以看不到,但是在跳转的时候,如果自定义的TabBar移动的速度跟系统页面移动的速度不一致,那么那个黑色的部分就会在跳转的过程中显示出来(可能描述得不是很清楚,大家可以屏蔽动画看一下效果)。


这里放上源码的下载地址:http://download.csdn.net/detail/smk524198002/6201655

希望大家多多批评指正,谢谢。

没有更多推荐了,返回首页