網易新聞實戰總結

為期兩天的網易新聞簡單完成,其中還有許多模糊的點,在此發文:
  • 一是為了自己總結思路以及再次貫徹一下整個小demo的細節操作
  • 二是回顧一下比較遺忘容易忽略的知識點
  • 三是為了激勵自己的開發興趣,順便分享給大家,共同享受iOS所帶來的開發樂趣吧

示例demo:(ps:最后做分類模塊字體滑動有個陰影bug 有懂得大牛求幫忙解決感謝感謝)

網易新聞.gif

好咯,接下來就開始我的實現之路吧~

####第一步:環境的配置(cocoaPods安裝指南)
#安裝CocoaPods
### 查看當前的源
sudo gem sources -l

### 添加源
sudo gem sources -a https://ruby.taobao.org/

### 刪除源
sudo gem sources -r https://rubygems.org/
### 安裝
sudo gem install cocoapods  
pod setup

***
#使用CocoaPods

### 搜索
pod search AFNetworking
### 生成 Podfile
echo "pod 'AFNetworking'" > Podfile
### 安裝
pod install
### 升級
pod update
由于本demo為抓包獲取網易新聞的JSON 我所采用的是第三方框架<AFN> 異步下載網絡圖片也是使用它自帶的UIImage的分類
  • 第一步:自定義工具類獲取單例對象(繼承與AFHTTPSessionManager)
    #import "HMNetworkTools.h"
    @implementation HMNetworkTools
    + (instancetype)sharedNetworkTools{
    static HMNetworkTools *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{

     NSURL *baseURL = [NSURL URLWithString:@"http://c.m.163.com/nc/"];
      
      NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
      
      //配置超時時長
      config.timeoutIntervalForRequest = 30;
    
      instance = [[self alloc]initWithBaseURL:baseURL sessionConfiguration:config];
       });
    
      //設置轉換模式
      instance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html",@"text/json",     @"text/javascript", nil];
    
      return instance;
      }
    
    @end
    
  • 第二步:實現的就是圖片輪播器的那個效果


    7866A03C-A4C9-48F3-A3A1-1BF86F8743F7.png

監聽網易新聞發送的HTTP請求,獲取請求數據的地址.根據獲取的數據創建圖片輪播器使用的模型類HeadLine

  • 創建模型類,設置需要的屬性

  • 封裝網絡操作

  • Controller中加載數據測試

  • 自定義cell顯示圖片

#import <Foundation/Foundation.h>

@interface HMHeadLine : NSObject

//定義屬性
@property (nonatomic,copy)NSString *title;

@property (nonatomic,copy)NSString *imgsrc;

+ (instancetype)headlineWithDict:(NSDictionary *)dict;

//放松異步請求獲取數據
+ (void)headlineWithSucess:(void(^)(NSArray *array))sucess error:(void(^)())error;

@end

異步發送請求獲取模型對象
#import "HMHeadLine.h"
#import "HMNetworkTools.h"
@implementation HMHeadLine

+ (instancetype)headlineWithDict:(NSDictionary *)dict{

HMHeadLine *headline = [self new];

[headline setValuesForKeysWithDictionary:dict];

return headline;

}

- (void)setValue:(id)value forUndefinedKey:(NSString *)key{

}

//獲取數據
+ (void)headlineWithSucess:(void (^)(NSArray *))sucess error:(void (^)())error{



[[HMNetworkTools sharedNetworkTools] GET:@"ad/headline/0-4.html" parameters:nil success:^(NSURLSessionDataTask *task, NSDictionary *responseObject) {
    
    //字典轉模型獲取數據
    //獲取第一個KEY
    NSString *rootKey = responseObject.keyEnumerator.nextObject;
    NSArray *array = responseObject[rootKey];
    
    NSMutableArray *marray = [NSMutableArray arrayWithCapacity:4];
    
    //循環遍歷獲取模型
    [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        HMHeadLine *model = [HMHeadLine headlineWithDict:obj];
        
        [marray addObject:model];
        
    }];
    
    if (sucess) {
        
        sucess(marray.copy);
    }
    
    
} failure:^(NSURLSessionDataTask *task, NSError *error) {
    
    if (error) {
        
    }
    
}];

}

@end

自定義cell

#import "HMHeadlineCell.h"
#import "HMHeadLine.h"
#import <UIImageView+AFNetworking.h>
@interface HMHeadlineCell ()

@property (weak, nonatomic) IBOutlet UIImageView *imgsrcView;

@property (weak, nonatomic) IBOutlet UILabel *titleView;

@property (weak, nonatomic) IBOutlet UIPageControl *pageControl;
@end

@implementation HMHeadlineCell

//從寫headline的方法
- (void)setHeadline:(HMHeadLine *)headline{

_headline = headline;

//解決重用問題
self.imgsrcView.image = nil;
self.titleView.text = nil;

//設置圖片
[self.imgsrcView setImageWithURL:[NSURL URLWithString:headline.imgsrc]];

//設置標題
self.titleView.text = headline.title;

self.pageControl.currentPage = self.tag;

}

@end

自定義CollectionViewControllView控制器實現數據源方法 加載數據實現圖片輪播器的效果

#import "HMImageLoopController.h"
#import "HMHeadLine.h"
#import "HMHeadlineCell.h"
@interface HMImageLoopController ()
@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *flowLaout;

//當前圖片的索引
@property (nonatomic, assign) NSInteger currentIndex;

//聲明一個屬性
@property (nonatomic,strong)NSArray *array;

@end

@implementation HMImageLoopController

- (void)viewDidLoad {
[super viewDidLoad];

//設置背景顏色
self.collectionView.backgroundColor = [UIColor whiteColor];

[HMHeadLine headlineWithSucess:^(NSArray *array) {
   
    self.array = array;
    
} error:^{
    
    NSLog(@"請求數據失敗");
    
}];

[self setCollectionViewStyle];

}

#pragma mark - 刷新數據
    - (void)setArray:(NSArray *)array{

_array = array;

[self.collectionView reloadData];

//永遠顯示第二個CELL
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:1 inSection:0];

[self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:0 animated:NO];
}

- (void)viewDidLayoutSubviews{

[super viewDidLayoutSubviews];

//設置cell的大小
self.flowLaout.itemSize = self.collectionView.frame.size;


}

#pragma mark - 設置collectionView的樣式
- (void)setCollectionViewStyle{


//設置滾動方向
self.flowLaout.scrollDirection = UICollectionViewScrollDirectionHorizontal;

self.flowLaout.minimumInteritemSpacing = 0;
self.flowLaout.minimumLineSpacing = 0;

self.collectionView.bounces = NO;
self.collectionView.pagingEnabled = YES;
self.collectionView.showsHorizontalScrollIndicator = NO;

    }

#pragma mark - 數據源方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

return self.array.count;
    }

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

//創建cell
HMHeadlineCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"headline" forIndexPath:indexPath];

//在滾動過程中下一張圖片的索引
//當滾動的過程中item的值可能是 0 或者 2
NSInteger index = (self.currentIndex + indexPath.item - 1 + self.array.count) % self.array.count;

cell.backgroundColor = [UIColor whiteColor];

cell.headline = self.array[index];

cell.tag = index;

return cell;
}
  //collectionView的代理方法
//滾動停止之后,把cell換成第二個cell
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
//計算下一張圖片的索引 (+1  -1)
//返回的值始終是 (0  2) - 1
int offset = scrollView.contentOffset.x / scrollView.bounds.size.width - 1;
self.currentIndex = (self.currentIndex + offset + self.array.count ) % self.array.count;


//始終顯示第二個cell
//主隊列的執行特點:先等待主線程上的代碼都執行完畢,再執行隊列中的任務
dispatch_async(dispatch_get_main_queue(), ^{
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:1 inSection:0];
    [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:0 animated:NO];
});


        }

@end

第三步:實現新聞列表模塊-實現數據的顯示及刷新數據(圖文混排效果,單圖,大圖,及三張圖片顯示的效果)

  • 利用containerView 將圖片輪播器加載到一個自定義tabelView上形成聯動
news.png

同理- 創建新聞列表模型對象,發送異步請求獲取數據,自定義tabelViewControllerView控制器及自定義cell加載數據

  • 創建模型
#import <Foundation/Foundation.h>

@interface HMNews : NSObject

//聲明屬性
@property (nonatomic,copy)NSString *imgsrc;
@property (nonatomic,copy)NSString *digest;
@property (nonatomic,copy)NSNumber *replyCount;
@property (nonatomic,copy)NSString *title;

//聲明一個大圖屬性
@property (nonatomic,assign)BOOL imgType;

//聲明三張圖的屬性
@property (nonatomic, copy) NSArray *imgextra;

//定義方法
+ (instancetype)newsWithDict:(NSDictionary *)dict;

//發送異步請求獲取數據
+ (void)newsWithurlString:(NSString *)urlString Sucess:(void(^)(NSArray *array))sucessBlock error:(void(^)())errorBlock;

@end
  • 封裝并且回調實現異步發送請求獲取數據
#import "HMNews.h"
#import "HMNetworkTools.h"
@implementation HMNews

+ (instancetype)newsWithDict:(NSDictionary *)dict{

HMNews *news = [HMNews new];

[news setValuesForKeysWithDictionary:dict];

return news;
}

- (void)setValue:(id)value forUndefinedKey:(NSString *)key{

}

//發送異步請求獲取數據
+ (void)newsWithurlString:(NSString *)urlString Sucess:(void(^)(NSArray *array))sucessBlock error:(void(^)())errorBlock{

[[HMNetworkTools sharedNetworkTools] GET:urlString parameters:nil success:^(NSURLSessionDataTask *task, NSDictionary *responseObject) {
    
    //獲取KEY
    NSString *rootKey = responseObject.keyEnumerator.nextObject;
    
    //獲取數組
    NSArray *array = responseObject[rootKey];
    
    NSMutableArray *mArray = [NSMutableArray arrayWithCapacity:10];
    
    //遍歷數組獲取模型
    [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        HMNews *model = [HMNews newsWithDict:obj];
        
        [mArray addObject:model];
        
    }];
    
    if (sucessBlock) {
        
        sucessBlock(mArray.copy);
        
    }
    
    
} failure:^(NSURLSessionDataTask *task, NSError *error) {
   
    if (errorBlock) {
    
        errorBlock();
    }
    
}];

}

@end
  • 自定義cell 實現新聞列表中所要求格式的新聞詳情列表

    #import <UIKit/UIKit.h>
    @class HMNews;
    @interface HMNewsCell : UITableViewCell
    
    //定義屬性屬性
    @property (nonatomic,strong)HMNews *news;
    
    //判斷是否為大圖cell
    + (NSString *)getReuseId:(HMNews *)news;
    
    //判斷行高
    + (CGFloat)getRowHeight:(HMNews *)news;
    @end
    
  • 實現自定義cell中的屬性賦值并且判斷圖片要求格式的要求進行圖片選擇

    #import "HMNewsCell.h"
    #import "HMNews.h"
    #import <UIImageView+AFNetworking.h>
    @interface HMNewsCell ()
    
    //聲明圖片,文字,摘要及回復數
    @property (weak, nonatomic) IBOutlet UIImageView *imgsrcView;
    @property (weak, nonatomic) IBOutlet UILabel *titleView;
    @property (weak, nonatomic) IBOutlet UILabel *digestView;
    @property (weak, nonatomic) IBOutlet UILabel *replyCount;
    
    @property (strong, nonatomic) IBOutletCollection(UIImageView) NSArray *imgextraViews;
    @end
    
    @implementation HMNewsCell
    
    //從寫news的set方法進行賦值
    - (void)setNews:(HMNews *)news{
    
    _news = news;
    
    //獲取圖片,文字,摘要及回復數
    [self.imgsrcView setImageWithURL:[NSURL URLWithString:news.imgsrc]];
    self.titleView.text = news.title;
    self.digestView.text = news.digest;
    self.replyCount.text = [NSString stringWithFormat:@"回帖數:%d",news.replyCount.intValue];
    
    //獲取數組中的照片
    [news.imgextra enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
      
      //獲取圖片的路徑
      NSString *imgsrc = obj[@"imgsrc"];
      
      UIImageView *imageView = self.imgextraViews[idx];
      
      [imageView setImageWithURL:[NSURL URLWithString:imgsrc]];
      
    }];
    
    }
    
    //判斷是否為大圖cell
    + (NSString *)getReuseId:(HMNews *)news{
    
        if (news.imgType) {
      //大圖
      return @"news1";
        }else if(news.imgextra){
      //三張圖
      return @"news2";
        }
    
        return @"news";
    }
    
    //判斷行高
    + (CGFloat)getRowHeight:(HMNews *)news{
    
        if (news.imgType) {
      //大圖
      return 200;
        }else if (news.imgextra){
      //三張圖
      return 150;
        }
    
        return 80;
    }
    
    @end
    
  • 在自定義控制器中實現請求并且實現他的數據源方法 實現新聞列表的數據展示
    #import "HMNewsController.h"
    #import "HMNews.h"
    #import "HMNewsCell.h"
    @interface HMNewsController ()

    //定義一個屬性
    @property (nonatomic,strong)NSArray *array;
    
    @end
    
    @implementation HMNewsController
    
    - (void)viewDidLoad {
    
        [super viewDidLoad];
    
    }
    
    - (void)setUrlString:(NSString *)urlString{
    
        //防止cell重用問題
        self.array = nil;
    
        [HMNews newsWithurlString:urlString Sucess:^(NSArray *array) {
      //獲取數據
      self.array = array;
        } error:^{
      NSLog(@"出錯");
        }];
    
    }
    
    #pragma mark - 異步操作刷新數據
    - (void)setArray:(NSArray *)array{
    
        _array = array;
    
        [self.tableView reloadData];
    
    }
    
    #pragma mark - 數據源方法
    
    - (NSInteger)tableView:(UITableView *)tableView       numberOfRowsInSection:(NSInteger)section {
    
        return self.array.count;
    }
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
        //1.獲取數據
        HMNews *news = self.array[indexPath.row];
    
        //2.創建cell
        HMNewsCell *cell = [tableView dequeueReusableCellWithIdentifier:[HMNewsCell getReuseId:news]];
    
        cell.news = news;
    
    
        return cell;
    
    }
    
    #pragma mark - 判斷cell的行高
    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
        //1.獲取數據
        HMNews *news = self.array[indexPath.row];
    
        return [HMNewsCell getRowHeight:news];
    
    }
    
    @end
    
  • 第四部:(PS:也是最為困難的一步:至今雖然代碼敲出來了 但是還是覺得很暈這里面就涉及到了控制器之間的關聯又能顯示滾動翻頁又要實現分類之間的滑動最重要就是數據的分類刷新---希望有大牛能幫我解釋一番)

  • 老樣子 現在要實現的是就是把之前寫的代碼都整合在一起放在一個自定義UIViewControllView中,設置根控制器為NavcontrollViewContrllView 在里面自控制器加入一個高度為44的scrollvIew及一個占下面的CollectView用來接受上面的兩個自定義類的數據 在根據JSON中的tname及tid 進行分類傳值刷新獲取不同新聞的列表 以及自定義的lbael的滾動.

在此-我會從寫創建一個StrobBord用來設置頁面到時候會從這里傳回數據

home.png
  • 這里所需要的模型數據就是從網易新聞的抓包獲取的資源JSON用來管理不同新聞的分類.

    #import <Foundation/Foundation.h>
    
    @interface HMChannel : NSObject
    
    //新聞的分類(頻道)
    @property (nonatomic,copy)NSString *tname;
    @property (nonatomic,copy)NSString *tid;
    
    //獲取請求數據網址
    @property (nonatomic,copy,readonly)NSString *urlString;
    
    + (instancetype)channelWithDict:(NSDictionary *)dict;
    
    //返回數組懶加載
    + (NSArray *)channelWithArray;
    
    @end
    
  • 懶加載數據獲取模型對象 并且實現網址的傳輸
    #import "HMChannel.h"

    @implementation HMChannel
    
    + (instancetype)channelWithDict:(NSDictionary *)dict{
    
        HMChannel *channel = [self new];
    
        [channel setValuesForKeysWithDictionary:dict];
    
        return channel;
    
    
    }
    
    - (void)setValue:(id)value forUndefinedKey:(NSString *)key{
    
    }
    
    //返回數組懶加載
    + (NSArray *)channelWithArray{
    
        //從本地加載數據
        NSString *path = [[NSBundle mainBundle]       pathForResource:@"topic_news.json" ofType:nil];
    
        NSData *data = [NSData dataWithContentsOfFile:path];
    
        //JSON的反序列化
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
    
        NSArray *array = dict[@"tList"];
    
        NSMutableArray *mArray = [NSMutableArray arrayWithCapacity:10];
    
        //遍歷數據  字典轉模型
        [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
      
            HMChannel *model = [HMChannel channelWithDict:obj];
      
            [mArray addObject:model];
      
        }];
    
        //對模型中的tid進行排序
        return [mArray sortedArrayUsingComparator:^NSComparisonResult(HMChannel *obj1, HMChannel *obj2) {
      
            return [obj1.tid compare:obj2.tid];
      
        }];
    
    }
    
    //獲取網絡地址
    - (NSString *)urlString{
    
        return [NSString stringWithFormat:@"article/headline/%@/0-140.html",self.tid];
    
    }
    
    @end
    
  • 自定義cell 在collectionView中實現NEWS stroboard 添加view 實現他的數據源方法 從新獲取新聞數據

  • Home.storyboard中collectionView的每一個cell都要去加載News.storyboard中的view,所以創建自定義cell。
    #import "HMHomeCell.h"
    #import "HMNewsController.h"

    @interface HMHomeCell ()
    
    @property (nonatomic,strong)HMNewsController *newsController;
    
    @end
    
    @implementation HMHomeCell
    
    //獲取數據
    - (void)awakeFromNib{
    
        //創建控制器加載View
        UIStoryboard *sb= [UIStoryboard storyboardWithName:@"News" bundle:nil];
    
        self.newsController = [sb instantiateInitialViewController];
    
        [self.contentView addSubview:self.newsController.view];
    
    }
    
    //設置view的大小
    - (void)layoutSubviews{
    
        [super layoutSubviews];
    
        self.newsController.view.frame = self.bounds;
    
    }
    
    - (void)setUrlString:(NSString *)urlString{
    
        self.newsController.urlString = urlString;
    
    }
    
    @end
    
  • 自定義lbl實現 滾動分類的實現(并且實現新聞頻道的標簽的縮放及位置的變化)

    #define kBIGFONT 18
    #define kSMALLFONT 14
    #import "HMChannelLabel.h"
    
    @implementation HMChannelLabel
    
    + (instancetype)channelLabelWithTName:(NSString *)tname{
    
        HMChannelLabel *lbl = [self new];
        lbl.text = tname;
        lbl.textAlignment = NSTextAlignmentCenter;
    
        //設置lbl大小
        lbl.font = [UIFont systemFontOfSize:kBIGFONT];
    
        [lbl sizeToFit];
    
        //lbl默認大小
        lbl.font = [UIFont systemFontOfSize:kSMALLFONT];
    
        return lbl;
    }
    
    - (void)setScale:(CGFloat)scale{
    
        CGFloat max = kBIGFONT * 1.0 / kSMALLFONT - 1;
    
        self.transform = CGAffineTransformMakeScale( max*scale+1, max*scale+1);
        self.textColor = [UIColor colorWithRed:scale green:0 blue:0 alpha:1];
    
    }
    
    @end
    
  • PS 最后一步 就是實現整個新聞的大致排版 也就是實現數據的加載跟lbl的創建及新聞頻道分類滾動實現(lbl計算涉及數學運算比較多~ 不作為本項目的重點)但是不知道lbl滾動為什么會有陰影的出現 有哪位大牛能夠看錯求忘能解決BUG,不勝感激.

  #import "HMHomeController.h"
  #import "HMChannel.h"
  #import "HMChannelLabel.h"
  #import "HMHomeCell.h"
  @interface HMHomeController ()      <UICollectionViewDataSource,UICollectionViewDelegate>

  //聲明一個數組用來保存數據
  @property (nonatomic,strong)NSArray *channels;
  @property (weak, nonatomic) IBOutlet UIScrollView *scrollView;

  @property (weak, nonatomic) IBOutlet UICollectionView *cooectionView;

  @property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *flowLaout;

  //記錄當前lbl的的索引
  @property (nonatomic,assign)int currenIndex;
  @end

  @implementation HMHomeController

  #pragma mark - 懶加載
  - (NSArray *)channels{

      if (_channels == nil) {
    
          _channels = [HMChannel channelWithArray];
      }      

      return _channels;
  }

  - (void)viewDidLoad {
      [super viewDidLoad];

      //創建分類
      [self loadChannels];

      //設置item的大小及collettionView的屬性
      [self getCollectionView];

      //加載新聞分類
      [self loadChannels];

  }

  #pragma mark - 設置item的大小及collettionView的屬性
  - (void)getCollectionView{


      //設置間距
      self.flowLaout.minimumInteritemSpacing = 0;
      self.flowLaout.minimumLineSpacing = 0;
      self.flowLaout.scrollDirection =       UICollectionViewScrollDirectionHorizontal;

      //設置collectionView一些屬性
      self.cooectionView.bounces = NO;
      //分頁
      self.cooectionView.pagingEnabled = YES;
      //水平條
      self.cooectionView.showsHorizontalScrollIndicator = NO;

  }

  - (void)viewDidLayoutSubviews{

      [super viewDidLayoutSubviews];
      //設置cell大小
      self.flowLaout.itemSize = self.cooectionView.frame.size;

  }

  #pragma mark - 創建頻道中的分類
  - (void)loadChannels{

      //不讓控制器自動生成64的偏移
      self.automaticallyAdjustsScrollViewInsets = NO;

      CGFloat marginX = 5;
      CGFloat x = marginX;
      CGFloat y = 0;
      CGFloat h = self.scrollView.bounds.size.height;

      //利用循環獲取分類的名稱
      for (HMChannel *channel in self.channels) {
    
          //自定義label獲取數據
          HMChannelLabel *lbl = [HMChannelLabel channelLabelWithTName:channel.tname];
    
          //添加到scrollView中
          [self.scrollView addSubview:lbl];
    
          //設置frame  寬度就為字體本身的寬度
          lbl.frame = CGRectMake(x, y, lbl.bounds.size.width, h);
    
          x += lbl.bounds.size.width + marginX;
    
      }

      //scrollView滾動的范圍
      self.scrollView.contentSize = CGSizeMake(x, h);
      //取消水平滑動條
      self.scrollView.showsHorizontalScrollIndicator = NO;

      HMChannelLabel *lbl = self.scrollView.subviews[0];
      lbl.scale = 1;
  }

  #pragma mark - 尋找滾動時候下一個lbl
  //當collectionView滾動時候計算lbl的順序
  - (void)scrollViewDidScroll:(UIScrollView *)scrollView{

      //當前lbl
      HMChannelLabel *currentlbl = self.scrollView.subviews[self.currenIndex];

      //下一個lbl
      HMChannelLabel *nextlbl = nil;

      //遍歷當前可見cell的索引
for (NSIndexPath *indexPath in self.cooectionView.indexPathsForVisibleItems) {
    
          if (indexPath.item != self.currenIndex) {
        
              //就是下一個lbl
              nextlbl = self.scrollView.subviews[indexPath.item];
              break;
        
          }
    
          if (nextlbl == nil) {
        return;
          }
    
      }

      //獲取滾動的比例
      CGFloat nextScale = ABS(scrollView.contentOffset.x / scrollView.bounds.size.width - self.currenIndex);
      CGFloat currentScale = 1- nextScale;

      currentlbl.scale = currentScale;
      nextlbl.scale = nextScale;

      //計算currentlbl的位置
      self.currenIndex = scrollView.contentOffset.x /             scrollView.bounds.size.width;

  }

  #pragma mark - 當滾動結束后計算currentlbl
  - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{

      //居中顯示當前顯示的標簽
      HMChannelLabel *label = self.scrollView.subviews[self.currenIndex];
      CGFloat offset = label.center.x - self.scrollView.bounds.size.width * 0.5;
      CGFloat maxOffset = self.scrollView.contentSize.width - label.bounds.size.width - self.scrollView.bounds.size.width;

      if (offset < 0) {
          offset = 0;
      } else if (offset > maxOffset) {
          offset = maxOffset + label.bounds.size.width;
      }

      [self.scrollView setContentOffset:CGPointMake(offset, 0) animated:YES];



  }

  #pragma mark - 數據源方法
  - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{

      return self.channels.count;
  }      

  - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

      //獲取數據
      HMChannel *channel = self.channels[indexPath.item];

      //創建cell
      HMHomeCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"home" forIndexPath:indexPath];

      cell.urlString = channel.urlString;

      return cell;

  }

  @end
  • PS 最后一步 就是實現整個新聞的大致排版 也就是實現數據的加載跟lbl的創建及新聞頻道分類滾動實現(lbl計算涉及數學運算比較多~ 不作為本項目的重點)但是不知道lbl滾動為什么會有陰影的出現 有哪位大牛能夠看錯求忘能解決BUG,不勝感激.

由于第一次在簡書上寫項目 正如我開頭說的那樣 不求其他,只想對項目的整個思路再次貫穿一遍,順便分享分享給各位書友們,學習之路任重道遠,在乎是的對自己自身的要求跟習慣,只有在不斷的前行之中發現自己的舍與得,希望大家在這條充滿創新的道路上找到自己的那條殊途~

本人github地址:https://github.com/aryehToDog

iOS技術成長群:255032637 有愿意的小伙伴可以長期學習共勉!

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

推薦閱讀更多精彩內容