為期兩天的網(wǎng)易新聞簡單完成,其中還有許多模糊的點,在此發(fā)文:
- 一是為了自己總結(jié)思路以及再次貫徹一下整個小demo的細節(jié)操作
- 二是回顧一下比較遺忘容易忽略的知識點
- 三是為了激勵自己的開發(fā)興趣,順便分享給大家,共同享受iOS所帶來的開發(fā)樂趣吧
示例demo:(ps:最后做分類模塊字體滑動有個陰影bug 有懂得大牛求幫忙解決感謝感謝)
好咯,接下來就開始我的實現(xiàn)之路吧~
####第一步:環(huán)境的配置(cocoaPods安裝指南)
#安裝CocoaPods
### 查看當(dāng)前的源
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為抓包獲取網(wǎng)易新聞的JSON 我所采用的是第三方框架<AFN> 異步下載網(wǎng)絡(luò)圖片也是使用它自帶的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]; }); //設(shè)置轉(zhuǎn)換模式 instance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html",@"text/json", @"text/javascript", nil]; return instance; } @end
-
第二步:實現(xiàn)的就是圖片輪播器的那個效果
監(jiān)聽網(wǎng)易新聞發(fā)送的HTTP請求,獲取請求數(shù)據(jù)的地址.根據(jù)獲取的數(shù)據(jù)創(chuàng)建圖片輪播器使用的模型類HeadLine
創(chuàng)建模型類,設(shè)置需要的屬性
封裝網(wǎng)絡(luò)操作
Controller中加載數(shù)據(jù)測試
自定義cell顯示圖片
#import <Foundation/Foundation.h>
@interface HMHeadLine : NSObject
//定義屬性
@property (nonatomic,copy)NSString *title;
@property (nonatomic,copy)NSString *imgsrc;
+ (instancetype)headlineWithDict:(NSDictionary *)dict;
//放松異步請求獲取數(shù)據(jù)
+ (void)headlineWithSucess:(void(^)(NSArray *array))sucess error:(void(^)())error;
@end
異步發(fā)送請求獲取模型對象
#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{
}
//獲取數(shù)據(jù)
+ (void)headlineWithSucess:(void (^)(NSArray *))sucess error:(void (^)())error{
[[HMNetworkTools sharedNetworkTools] GET:@"ad/headline/0-4.html" parameters:nil success:^(NSURLSessionDataTask *task, NSDictionary *responseObject) {
//字典轉(zhuǎn)模型獲取數(shù)據(jù)
//獲取第一個KEY
NSString *rootKey = responseObject.keyEnumerator.nextObject;
NSArray *array = responseObject[rootKey];
NSMutableArray *marray = [NSMutableArray arrayWithCapacity:4];
//循環(huán)遍歷獲取模型
[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;
//設(shè)置圖片
[self.imgsrcView setImageWithURL:[NSURL URLWithString:headline.imgsrc]];
//設(shè)置標題
self.titleView.text = headline.title;
self.pageControl.currentPage = self.tag;
}
@end
自定義CollectionViewControllView控制器實現(xiàn)數(shù)據(jù)源方法 加載數(shù)據(jù)實現(xiàn)圖片輪播器的效果
#import "HMImageLoopController.h"
#import "HMHeadLine.h"
#import "HMHeadlineCell.h"
@interface HMImageLoopController ()
@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *flowLaout;
//當(dāng)前圖片的索引
@property (nonatomic, assign) NSInteger currentIndex;
//聲明一個屬性
@property (nonatomic,strong)NSArray *array;
@end
@implementation HMImageLoopController
- (void)viewDidLoad {
[super viewDidLoad];
//設(shè)置背景顏色
self.collectionView.backgroundColor = [UIColor whiteColor];
[HMHeadLine headlineWithSucess:^(NSArray *array) {
self.array = array;
} error:^{
NSLog(@"請求數(shù)據(jù)失敗");
}];
[self setCollectionViewStyle];
}
#pragma mark - 刷新數(shù)據(jù)
- (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];
//設(shè)置cell的大小
self.flowLaout.itemSize = self.collectionView.frame.size;
}
#pragma mark - 設(shè)置collectionView的樣式
- (void)setCollectionViewStyle{
//設(shè)置滾動方向
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 - 數(shù)據(jù)源方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return self.array.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
//創(chuàng)建cell
HMHeadlineCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"headline" forIndexPath:indexPath];
//在滾動過程中下一張圖片的索引
//當(dāng)滾動的過程中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
//主隊列的執(zhí)行特點:先等待主線程上的代碼都執(zhí)行完畢构眯,再執(zhí)行隊列中的任務(wù)
dispatch_async(dispatch_get_main_queue(), ^{
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:1 inSection:0];
[self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:0 animated:NO];
});
}
@end
第三步:實現(xiàn)新聞列表模塊-實現(xiàn)數(shù)據(jù)的顯示及刷新數(shù)據(jù)(圖文混排效果,單圖,大圖,及三張圖片顯示的效果)
- 利用containerView 將圖片輪播器加載到一個自定義tabelView上形成聯(lián)動
同理- 創(chuàng)建新聞列表模型對象,發(fā)送異步請求獲取數(shù)據(jù),自定義tabelViewControllerView控制器及自定義cell加載數(shù)據(jù)
- 創(chuàng)建模型
#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;
//發(fā)送異步請求獲取數(shù)據(jù)
+ (void)newsWithurlString:(NSString *)urlString Sucess:(void(^)(NSArray *array))sucessBlock error:(void(^)())errorBlock;
@end
- 封裝并且回調(diào)實現(xiàn)異步發(fā)送請求獲取數(shù)據(jù)
#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{
}
//發(fā)送異步請求獲取數(shù)據(jù)
+ (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;
//獲取數(shù)組
NSArray *array = responseObject[rootKey];
NSMutableArray *mArray = [NSMutableArray arrayWithCapacity:10];
//遍歷數(shù)組獲取模型
[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 實現(xiàn)新聞列表中所要求格式的新聞詳情列表
#import <UIKit/UIKit.h> @class HMNews; @interface HMNewsCell : UITableViewCell //定義屬性屬性 @property (nonatomic,strong)HMNews *news; //判斷是否為大圖cell + (NSString *)getReuseId:(HMNews *)news; //判斷行高 + (CGFloat)getRowHeight:(HMNews *)news; @end
-
實現(xiàn)自定義cell中的屬性賦值并且判斷圖片要求格式的要求進行圖片選擇
#import "HMNewsCell.h" #import "HMNews.h" #import <UIImageView+AFNetworking.h> @interface HMNewsCell () //聲明圖片,文字,摘要及回復(fù)數(shù) @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; //獲取圖片,文字,摘要及回復(fù)數(shù) [self.imgsrcView setImageWithURL:[NSURL URLWithString:news.imgsrc]]; self.titleView.text = news.title; self.digestView.text = news.digest; self.replyCount.text = [NSString stringWithFormat:@"回帖數(shù):%d",news.replyCount.intValue]; //獲取數(shù)組中的照片 [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
-
在自定義控制器中實現(xiàn)請求并且實現(xiàn)他的數(shù)據(jù)源方法 實現(xiàn)新聞列表的數(shù)據(jù)展示
#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) { //獲取數(shù)據(jù) self.array = array; } error:^{ NSLog(@"出錯"); }]; } #pragma mark - 異步操作刷新數(shù)據(jù) - (void)setArray:(NSArray *)array{ _array = array; [self.tableView reloadData]; } #pragma mark - 數(shù)據(jù)源方法 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return self.array.count; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { //1.獲取數(shù)據(jù) HMNews *news = self.array[indexPath.row]; //2.創(chuàng)建cell HMNewsCell *cell = [tableView dequeueReusableCellWithIdentifier:[HMNewsCell getReuseId:news]]; cell.news = news; return cell; } #pragma mark - 判斷cell的行高 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{ //1.獲取數(shù)據(jù) HMNews *news = self.array[indexPath.row]; return [HMNewsCell getRowHeight:news]; } @end
第四部:(PS:也是最為困難的一步:至今雖然代碼敲出來了 但是還是覺得很暈這里面就涉及到了控制器之間的關(guān)聯(lián)又能顯示滾動翻頁又要實現(xiàn)分類之間的滑動最重要就是數(shù)據(jù)的分類刷新---希望有大牛能幫我解釋一番)
老樣子 現(xiàn)在要實現(xiàn)的是就是把之前寫的代碼都整合在一起放在一個自定義UIViewControllView中,設(shè)置根控制器為NavcontrollViewContrllView 在里面自控制器加入一個高度為44的scrollvIew及一個占下面的CollectView用來接受上面的兩個自定義類的數(shù)據(jù) 在根據(jù)JSON中的tname及tid 進行分類傳值刷新獲取不同新聞的列表 以及自定義的lbael的滾動.
在此-我會從寫創(chuàng)建一個StrobBord用來設(shè)置頁面到時候會從這里傳回數(shù)據(jù)
-
這里所需要的模型數(shù)據(jù)就是從網(wǎng)易新聞的抓包獲取的資源JSON用來管理不同新聞的分類.
#import <Foundation/Foundation.h> @interface HMChannel : NSObject //新聞的分類(頻道) @property (nonatomic,copy)NSString *tname; @property (nonatomic,copy)NSString *tid; //獲取請求數(shù)據(jù)網(wǎng)址 @property (nonatomic,copy,readonly)NSString *urlString; + (instancetype)channelWithDict:(NSDictionary *)dict; //返回數(shù)組懶加載 + (NSArray *)channelWithArray; @end
-
懶加載數(shù)據(jù)獲取模型對象 并且實現(xiàn)網(wǎng)址的傳輸
#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{ } //返回數(shù)組懶加載 + (NSArray *)channelWithArray{ //從本地加載數(shù)據(jù) 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]; //遍歷數(shù)據(jù) 字典轉(zhuǎn)模型 [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]; }]; } //獲取網(wǎng)絡(luò)地址 - (NSString *)urlString{ return [NSString stringWithFormat:@"article/headline/%@/0-140.html",self.tid]; } @end
自定義cell 在collectionView中實現(xiàn)NEWS stroboard 添加view 實現(xiàn)他的數(shù)據(jù)源方法 從新獲取新聞數(shù)據(jù)
-
Home.storyboard中collectionView的每一個cell都要去加載News.storyboard中的view现喳,所以創(chuàng)建自定義cell。
#import "HMHomeCell.h"
#import "HMNewsController.h"@interface HMHomeCell () @property (nonatomic,strong)HMNewsController *newsController; @end @implementation HMHomeCell //獲取數(shù)據(jù) - (void)awakeFromNib{ //創(chuàng)建控制器加載View UIStoryboard *sb= [UIStoryboard storyboardWithName:@"News" bundle:nil]; self.newsController = [sb instantiateInitialViewController]; [self.contentView addSubview:self.newsController.view]; } //設(shè)置view的大小 - (void)layoutSubviews{ [super layoutSubviews]; self.newsController.view.frame = self.bounds; } - (void)setUrlString:(NSString *)urlString{ self.newsController.urlString = urlString; } @end
-
自定義lbl實現(xiàn) 滾動分類的實現(xiàn)(并且實現(xiàn)新聞頻道的標簽的縮放及位置的變化)
#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; //設(shè)置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 最后一步 就是實現(xiàn)整個新聞的大致排版 也就是實現(xiàn)數(shù)據(jù)的加載跟lbl的創(chuàng)建及新聞頻道分類滾動實現(xiàn)(lbl計算涉及數(shù)學(xué)運算比較多~ 不作為本項目的重點)但是不知道lbl滾動為什么會有陰影的出現(xiàn) 有哪位大牛能夠看錯求忘能解決BUG,不勝感激.
#import "HMHomeController.h"
#import "HMChannel.h"
#import "HMChannelLabel.h"
#import "HMHomeCell.h"
@interface HMHomeController () <UICollectionViewDataSource,UICollectionViewDelegate>
//聲明一個數(shù)組用來保存數(shù)據(jù)
@property (nonatomic,strong)NSArray *channels;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UICollectionView *cooectionView;
@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *flowLaout;
//記錄當(dāng)前l(fā)bl的的索引
@property (nonatomic,assign)int currenIndex;
@end
@implementation HMHomeController
#pragma mark - 懶加載
- (NSArray *)channels{
if (_channels == nil) {
_channels = [HMChannel channelWithArray];
}
return _channels;
}
- (void)viewDidLoad {
[super viewDidLoad];
//創(chuàng)建分類
[self loadChannels];
//設(shè)置item的大小及collettionView的屬性
[self getCollectionView];
//加載新聞分類
[self loadChannels];
}
#pragma mark - 設(shè)置item的大小及collettionView的屬性
- (void)getCollectionView{
//設(shè)置間距
self.flowLaout.minimumInteritemSpacing = 0;
self.flowLaout.minimumLineSpacing = 0;
self.flowLaout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
//設(shè)置collectionView一些屬性
self.cooectionView.bounces = NO;
//分頁
self.cooectionView.pagingEnabled = YES;
//水平條
self.cooectionView.showsHorizontalScrollIndicator = NO;
}
- (void)viewDidLayoutSubviews{
[super viewDidLayoutSubviews];
//設(shè)置cell大小
self.flowLaout.itemSize = self.cooectionView.frame.size;
}
#pragma mark - 創(chuàng)建頻道中的分類
- (void)loadChannels{
//不讓控制器自動生成64的偏移
self.automaticallyAdjustsScrollViewInsets = NO;
CGFloat marginX = 5;
CGFloat x = marginX;
CGFloat y = 0;
CGFloat h = self.scrollView.bounds.size.height;
//利用循環(huán)獲取分類的名稱
for (HMChannel *channel in self.channels) {
//自定義label獲取數(shù)據(jù)
HMChannelLabel *lbl = [HMChannelLabel channelLabelWithTName:channel.tname];
//添加到scrollView中
[self.scrollView addSubview:lbl];
//設(shè)置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
//當(dāng)collectionView滾動時候計算lbl的順序
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
//當(dāng)前l(fā)bl
HMChannelLabel *currentlbl = self.scrollView.subviews[self.currenIndex];
//下一個lbl
HMChannelLabel *nextlbl = nil;
//遍歷當(dāng)前可見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 - 當(dāng)滾動結(jié)束后計算currentlbl
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
//居中顯示當(dāng)前顯示的標簽
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 - 數(shù)據(jù)源方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return self.channels.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
//獲取數(shù)據(jù)
HMChannel *channel = self.channels[indexPath.item];
//創(chuàng)建cell
HMHomeCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"home" forIndexPath:indexPath];
cell.urlString = channel.urlString;
return cell;
}
@end
- PS 最后一步 就是實現(xiàn)整個新聞的大致排版 也就是實現(xiàn)數(shù)據(jù)的加載跟lbl的創(chuàng)建及新聞頻道分類滾動實現(xiàn)(lbl計算涉及數(shù)學(xué)運算比較多~ 不作為本項目的重點)但是不知道lbl滾動為什么會有陰影的出現(xiàn) 有哪位大牛能夠看錯求忘能解決BUG,不勝感激.
由于第一次在簡書上寫項目 正如我開頭說的那樣 不求其他,只想對項目的整個思路再次貫穿一遍,順便分享分享給各位書友們,學(xué)習(xí)之路任重道遠,在乎是的對自己自身的要求跟習(xí)慣,只有在不斷的前行之中發(fā)現(xiàn)自己的舍與得,希望大家在這條充滿創(chuàng)新的道路上找到自己的那條殊途~
本人github地址:https://github.com/aryehToDog
iOS技術(shù)成長群:255032637 有愿意的小伙伴可以長期學(xué)習(xí)共勉!
2015.12.02