UI:UICollectionView

#import "ViewController.h"
#import "HeaderView.h"
#import "FooterView.h"

@interface ViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>//提供数据源协议,提供用户交互操作协议

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   self.navigationItem.title = @"集合视图";
    //UICollectionView 集合视图、支持竖直和水平方向滑动
    UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
    UICollectionView * collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:layout];
    [self.view addSubview:collectionView];
    //为它配置属性
    //为layout 配置属性
    //设置每一个 item 的大小 (每一个小图的大小哦)
    layout.itemSize = CGSizeMake(100, 100);
    //配置底层边界大小,缩进量(上、下、左、右)
    layout.sectionInset = UIEdgeInsetsMake(5, 10, 10, 5);
    //设置每一行cell的最小的间距
    layout.minimumLineSpacing = 15;
    //设置item 的最小间距
    layout.minimumInteritemSpacing = 10;
    //设置滑动方向
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    [self.view addSubview:collectionView];
    //配置代理
    collectionView.delegate = self;
    //配置数据源
    collectionView.dataSource = self;
    //设置页眉页脚
    layout.headerReferenceSize = CGSizeMake(0, 30);
    layout.footerReferenceSize = CGSizeMake(0, 40);
    //设置背景颜色
    collectionView.backgroundColor = [UIColor blackColor];
    [layout release];
    [collectionView release];
    
    //注册系统提供的 cell
    [collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"reues"];
    [self regesiterCell];//注册 cell
}

-(void)regesiterCell{
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark----提供数据源
//提供分区的 item 数目 <必须实现>
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 9;
}
//提供分区的个数。默认是一个分区

//返回 cell <必须实现>
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    //要先注册 cell
    UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reues" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor orangeColor];
    //注册页眉
    [collectionView registerClass:[HeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headercell"];
    [collectionView registerClass:[FooterView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footercell"];
    return cell;
}
//返回对应页眉的视图
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        //返回对应的页眉
        HeaderView * hview = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"headercell" forIndexPath:indexPath];
        hview.titleLabel.text = @"页眉";
        hview.titleLabel.tintColor = [UIColor whiteColor];
        return hview;
    }else{
        //返回页脚
        FooterView * fview = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footercell" forIndexPath:indexPath];
        fview.titleLabel.text = @"页脚";
        return fview;
    }
}

//设置分区的数目
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 3;
}

#pragma mark----处理用户交互的协议
//点击每一个 item 进入不同的页面
//选中每一个 Item 时候出发的方法,可以进行页面的跳转,或者 push 到某一个界面
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    //分区位置(Section)   以及所在分区第几个的位置(row)
    NSLog(@"%ld %ld",(long)indexPath.item,(long)indexPath.row);
    NSLog(@"%ld %ld",(long)indexPath.section,(long)indexPath.row);
}
View Code UICollectionView基础知识

 

用layout 配置相同风格的cell .用 协议的方法可以动态的配置想要的 cell 风格.

在使用 UIcollectionView 的时候,对应要注册的 cell 是一个UIcollectionViewCell 的对象

1.瀑布流的效果,根据自己的需求配置相关的属性。

2.我们经常使用的第三方类,(需要我们使用 pod 命令引入)如 :AFNetworking、FMDB、MBProgressHUD、SDWebImage 等等。

 

 代码:
———————————————————————————————————————————————(.h文件)


———————————————————————————————————————————————(.m文件)

#import "AppDelegate.h"
#import "ViewController.h"

@interface AppDelegate ()

@end

@implementation AppDelegate
-(void)dealloc{
    [_window release];
    [super dealloc];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    ViewController * VC = [[ViewController alloc]init];
    UINavigationController * navl = [[UINavigationController alloc]initWithRootViewController:VC];
    self.window.rootViewController = navl;
    [VC release];
    [navl release];
    
    return YES;
}
View Code Appdelegate文件
———————————————————————————————————————————————(.h文件)


#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@end


———————————————————————————————————————————————(.m文件)


#import "ViewController.h"
#import "HeaderView.h"
#import "FooterView.h"
#import "CollectionViewCell.h"

@interface ViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>//提供数据源协议,提供用户交互操作协议

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   self.navigationItem.title = @"集合视图";
    //UICollectionView 集合视图、支持竖直和水平方向滑动
    UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
    UICollectionView * collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:layout];
    [self.view addSubview:collectionView];
    //为它配置属性
    //为layout 配置属性
    //设置每一个 item 的大小 (每一个小图的大小哦)
    layout.itemSize = CGSizeMake(100, 160);
    //配置底层边界大小,缩进量(上、下、左、右)
    layout.sectionInset = UIEdgeInsetsMake(5, 10, 10, 5);
    //设置每一行cell的最小的间距
    layout.minimumLineSpacing = 15;
    //设置item 的最小间距
    layout.minimumInteritemSpacing = 10;
    //设置滑动方向
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    [self.view addSubview:collectionView];
    //配置代理
    collectionView.delegate = self;
    //配置数据源
    collectionView.dataSource = self;
    //设置页眉页脚
    layout.headerReferenceSize = CGSizeMake(0, 30);
    layout.footerReferenceSize = CGSizeMake(0, 40);
    //设置背景颜色
    collectionView.backgroundColor = [UIColor blackColor];
    [layout release];
    [collectionView release];
    
    //注册系统提供的 cell
    [collectionView registerClass:[CollectionViewCell class] forCellWithReuseIdentifier:@"reues"];
    [self regesiterCell];//注册 cell
}

-(void)regesiterCell{
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark----提供数据源
//提供分区的 item 数目 <必须实现>
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 7;
}
//提供分区的个数。默认是一个分区

//返回 cell <必须实现>
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    //要先注册 cell
    CollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reues" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor orangeColor];
    cell.imageview.frame =cell.bounds;
    cell.label.frame = CGRectMake(0, cell.frame.size.height - 30, cell.frame.size.width, 30);
    //注册页眉
    [collectionView registerClass:[HeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headercell"];
    [collectionView registerClass:[FooterView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footercell"];
    return cell;
}
//返回对应页眉的视图
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        //返回对应的页眉
        HeaderView * hview = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"headercell" forIndexPath:indexPath];
        hview.titleLabel.text = @"页眉";
        hview.titleLabel.tintColor = [UIColor whiteColor];
        return hview;
    }else{
        //返回页脚
        FooterView * fview = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footercell" forIndexPath:indexPath];
        fview.titleLabel.text = @"页脚";
        return fview;
    }
}

//设置分区的数目
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 5;
}

#pragma mark----处理用户交互的协议
//点击每一个 item 进入不同的页面
//选中每一个 Item 时候出发的方法,可以进行页面的跳转,或者 push 到某一个界面
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    //分区位置(Section)   以及所在分区第几个的位置(row)
    NSLog(@"%ld %ld",(long)indexPath.item,(long)indexPath.row);
    NSLog(@"%ld %ld",(long)indexPath.section,(long)indexPath.row);
}

#pragma mark ------配置 cell 的协议
//动态的配置 cell 要实现的协议
//动态的配置每个分区的 item 的 size 大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    //每次创键一个 item 都要执行该方法,页面会自己计算如何放置
    if (indexPath.section == 0) {
        return CGSizeMake(100, 160);
    }
    return CGSizeMake(80, 160);
}
//页面的缩进量。是一个结构体
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    //动态的为每一个分区去配置他的缩进量
    if (section == 0) {
        return UIEdgeInsetsMake(10, 5, 10, 5);
    }
    return UIEdgeInsetsMake(0, 5, 0, 5);
}
//动态配置 item 之间最小的间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return section == 0 ? 10 : 5;
}
//动态设置 item 最小的行间值
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 10;
}
//动态设置页眉的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return CGSizeMake(self.view.frame.size.width, 10);
    }
    if (section == 1) {
      return CGSizeMake(self.view.frame.size.width, 25);
    }
    return CGSizeMake(self.view.frame.size.width, 35);
}
//动态设置页脚的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    if (section == 0) {
        return CGSizeMake(self.view.frame.size.width, 10);
    }
    if (section == 1) {
        return CGSizeMake(self.view.frame.size.width, 25);
    }
    return CGSizeMake(self.view.frame.size.width, 35);
}
/*
#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
View Code ViewController文件
———————————————————————————————————————————————(.h文件)


#import <UIKit/UIKit.h>

@interface CollectionViewCell : UICollectionViewCell
@property(nonatomic,retain)UIImageView * imageview;
@property(nonatomic,retain)UILabel * label;
@end


———————————————————————————————————————————————(.m文件)



#import "CollectionViewCell.h"

//自定义的cell
@implementation CollectionViewCell

-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self.contentView addSubview:self.imageview];
        [self.contentView addSubview:self.label];
    }
    return self;
}
-(UIImageView *)imageview{
    if (!_imageview) {
        self.imageview = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height - 30)];
        [_imageview setImage:[UIImage imageNamed:@"1"]];
    }
    return [[_imageview retain]autorelease];
}
-(UILabel *)label{
    if (!_label) {
        self.label = [[UILabel alloc]initWithFrame:CGRectMake(0, self.frame.size.height - 30, self.frame.size.width, 30)];
        _label.backgroundColor = [UIColor brownColor];
        _label.text = @"自定义cell 的 Label ";
    }
    return [[_label retain]autorelease];
}
@end
View Code CollectionViewCell文件
———————————————————————————————————————————————(.h文件)

#import <UIKit/UIKit.h>

@interface HeaderView : UICollectionReusableView
@property(nonatomic,retain)UILabel * titleLabel;
@end


———————————————————————————————————————————————(.m文件)



#import "HeaderView.h"

@implementation HeaderView

-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        //分区的页眉根据需要去设置 可为 Label 视图 等等
        [self addSubview:self.titleLabel];
    }
    return self;
}

-(UILabel *)titleLabel{
    if (!_titleLabel) {
        self.titleLabel = [[UILabel alloc]initWithFrame:self.bounds];
        _titleLabel.textColor = [UIColor blackColor];
        _titleLabel.backgroundColor = [UIColor whiteColor];
        _titleLabel.textAlignment = UITextAlignmentCenter;
    }
    return [[_titleLabel retain]autorelease];
}
-(void)dealloc{
    self.titleLabel = nil;
    [super dealloc];
}
@end
View Code HeaderView文件
———————————————————————————————————————————————(.h文件)
#import <UIKit/UIKit.h>

@interface FooterView : UICollectionReusableView
@property(nonatomic,retain)UILabel * titleLabel;
@end


———————————————————————————————————————————————(.m文件)


#import "FooterView.h"

@implementation FooterView
-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        //分区的页眉根据需要去设置 可为 Label 视图 等等
        [self addSubview:self.titleLabel];
    }
    return self;
}

-(UILabel *)titleLabel{
    if (!_titleLabel) {
        self.titleLabel = [[UILabel alloc]initWithFrame:self.bounds];
        _titleLabel.textColor = [UIColor blackColor];
        _titleLabel.textAlignment = UITextAlignmentCenter;
        _titleLabel.backgroundColor = [UIColor brownColor];
    }
    return [[_titleLabel retain]autorelease];

}
-(void)dealloc{
    self.titleLabel = nil;
    [super dealloc];
}
@end
View Code FooterView文件

 

 在解析JSON数据的时候注意,截取字符串后需要用一个字符串对象接收一下。

本项目的字典的操作,出现的问题。
     [_dicBase setObject:rating  forKey:@"rating"];//rating 是从上面传来的字符串对象 这样写并没有存入字典

    [_dicBase setDictionary:@{@"sdg":@"dfg"}];//这样就存入了字典

    [_dicBase setDictionary:@{@"title":title}];//存入字典成功

 

代码:

———————————————————————————————————————————————(.h文件)


———————————————————————————————————————————————(.m文件)

#import "AppDelegate.h"
#import "MoveListViewController.h"

@interface AppDelegate ()

@end

@implementation AppDelegate
-(void)dealloc{
    [_window  release];
    [super dealloc];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    MoveListViewController * moveVC = [[MoveListViewController alloc]init];
    UINavigationController * navl = [[UINavigationController alloc]initWithRootViewController:moveVC];
    self.window.rootViewController = navl;
    
    
    [navl release];
    [moveVC release];
    
    return YES;
}
View Code Appdelegate文件
———————————————————————————————————————————————(.h文件)

#import <UIKit/UIKit.h>

@interface MoveListViewController : UIViewController

@end

———————————————————————————————————————————————(.m文件)


#define kMovieListUrl @"http://api.douban.com/v2/movie/nowplaying?app_name=doubanmovie&client=e:iPhone4,1%7Cy:iPhoneOS_6.1%7Cs:mobile%7Cf:doubanmovie_2%7Cv:3.3.1%7Cm:PP_market%7Cudid:aa1b815b8a4d1e961347304e74b9f9593d95e1c5&alt=json&city=%E5%8C%97%E4%BA%ACversion=2&apikey=0df993c66c0c636e29ecbb5344252a4a"
#import "MoveListViewController.h"
#import "AFNetworking.h"
#import "model.h"
#import "UIImageView+WebCache.h"//第三方异步缓存机制
#import "MoveCell.h"
#import "MBProgressHUD.h"
#import "DetailViewController.h"

//豆瓣的电影这一个模块
@interface MoveListViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
@property(nonatomic,retain)UICollectionView * collectionView;
@property(nonatomic,retain)NSMutableArray * dataSource;//存放数据源

@end

@implementation MoveListViewController

-(NSMutableArray *)dataSource{
    if (!_dataSource) {
        self.dataSource = [NSMutableArray arrayWithCapacity:1];
    }
    return _dataSource;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"电影页面";
    [self sublayView];//布局页面
    self.navigationController.navigationBar.translucent = NO;
}

-(void)sublayView{
    UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
    self.collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:layout];
    //设置代理
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    //设置 item 的大小尺寸
    layout.itemSize = CGSizeMake((self.view.frame.size.width - 60 )/3, 100);
    layout.minimumInteritemSpacing = 10;
    layout.minimumLineSpacing = 10;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    //提供数据源和交互
    //注册 cell
    [self.collectionView registerClass:[MoveCell class] forCellWithReuseIdentifier:@"reues"];
    //缩进值
    layout.sectionInset = UIEdgeInsetsMake(5, 10, 5, 5);
    //请求数据
    [self requeData];
    [self.view addSubview:self.collectionView];
}
//请求数据
-(void)requeData{
    //显示透明指示框
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    AFHTTPRequestOperationManager * manage = [AFHTTPRequestOperationManager manager];
    __block MoveListViewController * vc = self;
    [manage GET:kMovieListUrl parameters:nil success: ^void(AFHTTPRequestOperation * operatioon, id responseObject) {
            [vc parseData:responseObject];
        } failure:^void(AFHTTPRequestOperation * operatioon, NSError * error) {
            NSLog(@"%@",error);
        }];
}

-(void)parseData:(NSDictionary *)dic{
    //隐藏指示框
    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    NSArray * arr = dic[@"entries"];
    for (NSDictionary * dd in arr) {
        model * mm = [[model alloc]initWithDIc:dd];
        [self.dataSource addObject:mm];
        [mm release];
    }
    [self.collectionView reloadData];//
}
#pragma mark----设置数据源
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataSource.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    MoveCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reues" forIndexPath:indexPath];
    model * per = self.dataSource[indexPath.item];//写成 row 也可以
    cell.titleLabel.text = per.title;
    cell.posterView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:per.imageUrl]]];
    return cell;
}
#pragma mark-----处理点击事件
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    DetailViewController * detailVc =[[DetailViewController alloc]init];
    model * move = self.dataSource[indexPath.item];
    detailVc.idStr = move.ID;
    detailVc.moveTitle = move.title;
    [self.navigationController pushViewController:detailVc animated:YES];
    
}
- (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
View Code MoveListViewController文件
———————————————————————————————————————————————(.h文件)
#import <UIKit/UIKit.h>

@interface DetailViewController : UIViewController
@property(nonatomic,copy)NSString * idStr;
@property(nonatomic,copy)NSString * moveTitle;//不能取名为title 因为导航栏有一个 title
@end


———————————————————————————————————————————————(.m文件)

#define kMovieDetailUrl @"http://api.douban.com/v2/movie/subject/"

#import "DetailViewController.h"
#import "MoveDetailView.h"
#import "AFNetworking.h"

@interface DetailViewController ()
@property(nonatomic,retain)NSMutableArray * dataSource;
@property(nonatomic,retain)NSMutableDictionary * dicBase;//用于存储数据,方便收藏
@end

@implementation DetailViewController

-(NSMutableArray *)dataSource{
    if (!_dataSource) {
        self.dataSource = [NSMutableArray arrayWithCapacity:1];
    }
    return _dataSource;
}
-(void)loadView{
    MoveDetailView * detalView = [[MoveDetailView alloc]init];
    self.view = detalView;//不用再继承父类的方法,就是不用再去创建根视图
    [detalView release];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    //指定根视图,然后再去请求网络数据
    [self customizedNav];//私有导航条
    [self requestData];//请求数据
}

-(void)customizedNav{
    UIBarButtonItem * left = [[UIBarButtonItem alloc]initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(handleBack:)];
    self.navigationItem.leftBarButtonItem = left;
    [left release];
    
    UIBarButtonItem * right = [[UIBarButtonItem alloc]initWithTitle:@"收藏" style:UIBarButtonItemStylePlain target:self action:@selector(handleCollect:)];
    self.navigationItem.rightBarButtonItem = right;
    [right release];
    
    self.navigationItem.title = self.moveTitle;
}
//返回操作按钮
-(void)handleBack:(UIBarButtonItem *)sender{
    [self.navigationController popViewControllerAnimated:YES];
}
//收藏操作按钮
-(void)handleCollect:(UIBarButtonItem *)sender{

}
//请求数据
-(void)requestData{
    AFHTTPRequestOperationManager * manage = [AFHTTPRequestOperationManager manager];
    NSString * strUrl = [kMovieDetailUrl stringByAppendingString:self.idStr];
    [manage GET:strUrl parameters:nil success:^void(AFHTTPRequestOperation * operation, id responsObject) {
        //处理解析的数据
        [self praseWithData:responsObject];
//        NSLog(@"%@",responsObject);
    } failure:^void(AFHTTPRequestOperation * operation, NSError * error) {
        NSLog(@"%@",error);
    }];
    
}
-(void)praseWithData:(NSDictionary *)dic{
    NSString * title = dic[@"title"];
    NSString * rating_count = [[dic[@"ratings_count"] stringValue] stringByAppendingString:@"人评论"];
    NSNumberFormatter * numberFormater = [[NSNumberFormatter alloc]init];
    NSString * date =[[numberFormater stringFromNumber:dic[@"year"]] stringByAppendingString:@"年上映"];
    NSString * imageUrl = dic[@"images"][@"medium"];
    NSString * content = dic[@"summary"];
    NSString * time = dic[@"durations"];
    //对电影的类别的处理
    NSMutableString * type = [NSMutableString stringWithString:@""];
    for (NSString * str in dic[@"genres"]) {
        [type appendFormat:@"%@、",str];
    }
   NSString * strType =  [type substringToIndex:(type.length-1)];
    //电影的产地处理
    NSMutableString * address = [NSMutableString stringWithString:@""];
    for (NSString * str in dic[@"countries"]) {
        [address appendFormat:@"%@、",str];
    }
    NSString * addressStr =  [address  substringToIndex:(address.length-1)];

    //评分
    NSString * rating = [NSString stringWithFormat:@"评分:%@",dic[@"rating"][@"average"]];
    
    if (time.length > 0) {
        [(MoveDetailView *)self.view configureWithImage:imageUrl rating:rating ratingNum:rating_count ptime:[NSString stringWithFormat:@"2015年最新上映"] time:time general:strType countries:addressStr summary:content];
    }else{
         [(MoveDetailView *)self.view configureWithImage:imageUrl rating:rating ratingNum:rating_count ptime:[NSString stringWithFormat:@"2015年最新上映"] time:@"没有找到数据" general:strType countries:addressStr summary:content];
    }
    //保存到字典方便存储数据库
    self.dicBase = [[NSMutableDictionary alloc]init];
    //下面不能存入字典
//    [_dicBase setObject:title forKey:@"title"];
//    [_dicBase setObject:rating_count  forKey:@"ratings_count"];
//    [_dicBase setObject:[NSString stringWithFormat:@"2015年最新上映"] forKey:@"pubdate"];
//    [_dicBase setObject:imageUrl  forKey:@"imageUrl"];
//    [_dicBase setObject:content forKey:@"summary"];
//    [_dicBase setObject:addressStr  forKey:@"address"];
//    [_dicBase setObject:strType forKey:@"type"];
//    [_dicBase setObject:rating  forKey:@"rating"];
    //下面存入字典了
    [_dicBase setDictionary:@{@"title":title}];
    [_dicBase setDictionary:@{@"ratings_count":rating_count}];
    [_dicBase setDictionary:@{@"imageUrl":imageUrl}];
    [_dicBase setDictionary:@{@"summary":content}];
    [_dicBase setDictionary:@{@"address":addressStr}];
    [_dicBase setDictionary:@{@"type":strType}];
    [_dicBase setDictionary:@{@"rating":rating}];

}
-(void)viewDidDisappear:(BOOL)animated{
  
}
- (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
View Code DetailViewController文件
———————————————————————————————————————————————(.h文件)

#import <UIKit/UIKit.h>

@interface MoveDetailView : UIView

@property(nonatomic,retain)UIImageView * posterView;
@property(nonatomic,retain)UILabel * rating;
@property(nonatomic,retain)UILabel * rating_count;
@property(nonatomic,retain)UILabel * ptime;
@property(nonatomic,retain)UILabel * time;
@property(nonatomic,retain)UILabel * genernal;
@property(nonatomic,retain)UILabel * conutrise;
@property(nonatomic,retain)UILabel * summary;
@property(nonatomic,retain)UIScrollView * scroll;
//为控件赋值
-(void)configureWithImage:(NSString *)imageUrl
                   rating:(NSString *)rating
                ratingNum:(NSString *)ratingNum
                    ptime:(NSString *)ptime
                     time:(NSString *)time
                  general:(NSString *)genernal
                countries:(NSString *)countries
                  summary:(NSString *)summary;
@end


———————————————————————————————————————————————(.m文件)

#define FONTSIZE [UIFont systemFontOfSize:15]
#import "MoveDetailView.h"
#import "UIImageView+WebCache.h"
@implementation MoveDetailView

-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:[[UIScreen mainScreen] bounds]];
    if (self) {
        [self addSubview:self.scroll];
        [self setOtherView];
    }
    return self;
}

-(void)setOtherView{
    [self.scroll addSubview:self.posterView];
    [self.scroll addSubview:self.rating];
    [self.scroll addSubview:self.rating_count];
    [self.scroll addSubview:self.ptime];
    [self.scroll addSubview:self.time];
    [self.scroll addSubview:self.genernal];
    [self.scroll addSubview:self.conutrise];
    [self.scroll addSubview:self.summary];
    
    //测试yanse
//    self.posterView.backgroundColor = [UIColor redColor];
//    self.rating_count.backgroundColor = [UIColor grayColor];
//    self.rating.backgroundColor = [UIColor blackColor];
//    self.ptime.backgroundColor = [UIColor blueColor];
//    self.time.backgroundColor = [UIColor yellowColor];
//    self.genernal.backgroundColor = [UIColor blackColor];
//    self.conutrise.backgroundColor = [UIColor grayColor];
//    self.summary.backgroundColor = [UIColor brownColor];
}

-(UIScrollView *)scroll{
    if (!_scroll) {
        self.scroll = [[UIScrollView alloc]initWithFrame:self.bounds];
    }
    return [[_scroll retain]autorelease];
}
-(UIImageView *)posterView{
    if (!_posterView) {
        self.posterView = [[UIImageView alloc]initWithFrame:CGRectMake(40, 20, 100, 140)];
    }
    return [[_posterView retain]autorelease];
}
-(UILabel *)rating{
    if (!_rating) {
        self.rating = [[UILabel alloc]initWithFrame:CGRectMake(180, 20, 80, 20)];
        self.rating.font = FONTSIZE;
    }
    return [[_rating retain]autorelease];
}
-(UILabel *)rating_count{
    if (!_rating_count) {
        self.rating_count = [[UILabel alloc]initWithFrame:CGRectMake(260, 20, 100, 20)];
        self.rating_count.font = FONTSIZE;
    }
    return [[_rating_count retain]autorelease];
}
-(UILabel *)ptime{
    if (!_ptime) {
        self.ptime =[[UILabel alloc]initWithFrame:CGRectMake(180, 50, 200, 20)];
        self.ptime.font = FONTSIZE;
    }
    return [[_ptime retain]autorelease];
}
-(UILabel *)time{
    if (!_time) {
        self.time = [[UILabel alloc]initWithFrame:CGRectMake(180, 80, 100, 20)];
        self.time.font = FONTSIZE;
    }
    return [[_time retain]autorelease];
}
-(UILabel *)genernal{
    if (!_genernal) {
        self.genernal = [[UILabel alloc]initWithFrame:CGRectMake(180, 110, 200, 20)];
        self.genernal.font = FONTSIZE;
    }
    return [[_genernal retain]autorelease];
}
-(UILabel *)conutrise{
    if (!_conutrise) {
        self.conutrise = [[UILabel alloc]initWithFrame:CGRectMake(180, 140, 200, 20)];
        self.conutrise.font = FONTSIZE;
    }
    return [[_conutrise retain]autorelease];
}
-(UILabel *)summary{
    if (!_summary) {
        self.summary = [[UILabel alloc]init];
        _summary.numberOfLines = 0;//换行
    }
    return [[_summary retain]autorelease];
}
//计算文本的自适应高度
-(CGFloat)heightWithContent:(NSString *)summary{
    NSDictionary * dic = @{NSFontAttributeName:[UIFont systemFontOfSize:19]};
    return [summary boundingRectWithSize:CGSizeMake(self.frame.size.width, 1000) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:dic context:nil].size.height;
}

//为控件赋值
-(void)configureWithImage:(NSString *)imageUrl
                   rating:(NSString *)rating
                ratingNum:(NSString *)ratingNum
                    ptime:(NSString *)ptime
                     time:(NSString *)time
                  general:(NSString *)genernal
                countries:(NSString *)countries
                  summary:(NSString *)summary{
    //重新设置 frame
    self.summary.frame = CGRectMake(20, 160, self.frame.size.width - 40, [self heightWithContent:summary]);
    //scroll 自适应高度
    self.scroll.contentSize = CGSizeMake(self.frame.size.width, [self heightWithContent:summary] + 250);//加上
    [self.posterView sd_setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:[UIImage imageNamed:@"1.jpeg"]];
    self.rating.text = rating;
    self.rating_count.text = ratingNum;
    self.ptime.text = ptime;
    self.genernal.text = genernal;
    self.conutrise.text = countries;
    self.summary.text = summary;
    self.time.text = time;
}
View Code MoveDetailView文件
———————————————————————————————————————————————(.h文件)
#import <UIKit/UIKit.h>
@class model;

@interface MoveCell : UICollectionViewCell
@property(nonatomic,retain)UIImageView * posterView;
@property(nonatomic,retain)UILabel * titleLabel;
@property(nonatomic,retain)model * permodel;
@end


———————————————————————————————————————————————(.m文件)


#import "MoveCell.h"
#import "model.h"
#import "UIImageView+WebCache.h"
@implementation MoveCell
-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self.contentView addSubview:self.posterView];
        [self.contentView addSubview:self.titleLabel];
    }
    return self;
}
-(UIImageView *)posterView{
    if (!_posterView) {
        self.posterView =[[UIImageView alloc]initWithFrame:CGRectMake(0,0,self.frame.size.width,  self.frame.size.height - 30)];
    }
    return [[_posterView retain]autorelease];
}
-(UILabel *)titleLabel{
    if (!_titleLabel) {
        self.titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, self.frame.size.height - 30, self.frame.size.width, 30)];
        self.titleLabel.textAlignment = UITextAlignmentCenter;
        _titleLabel.font = [UIFont systemFontOfSize:15];
    }
    return [[_titleLabel retain]autorelease];
}

-(void)setPermodel:(model *)permodel{
    if (_permodel != permodel ) {
        [_permodel release];
        _permodel = [permodel retain];
    }
    [self.posterView sd_setImageWithURL:[NSURL URLWithString:permodel.imageUrl] placeholderImage:@"1"];
}
@end
View Code MoveCell文件
———————————————————————————————————————————————(.h文件)

#import <Foundation/Foundation.h>

@interface model : NSObject
@property(nonatomic,copy)NSString * ID;
@property(nonatomic,copy)NSString * title;
@property(nonatomic,copy)NSString * imageUrl;

-(instancetype)initWithDIc:(NSDictionary *)dic;
@end


———————————————————————————————————————————————(.m文件)

#import "model.h"

@implementation model
-(instancetype)initWithDIc:(NSDictionary *)dic{
    self = [super init];
    if (self) {
        [self setValuesForKeysWithDictionary:dic];
    }
    return self;
}
-(void)setValue:(id)value forUndefinedKey:(NSString *)key{
    //处理找不到的属性
    if ([key isEqualToString:@"id"]) {
        self.ID = value;
    }
    if ([key isEqualToString:@"images"]) {
        self.imageUrl = value[@"medium"];
    }
}
View Code model文件
———————————————————————————————————————————————(.h文件)

#import <Foundation/Foundation.h>

@interface SqlHelper : NSObject
//创建一个单例方法
+(SqlHelper *)defaultSqlHelper;
//创建用于存储数据的属性字段
//@property(nonatomic,copy)NSString * 
@end

———————————————————————————————————————————————(.m文件)


#import "SqlHelper.h"
#import "FMDB.h"

@implementation SqlHelper

static SqlHelper * helper = nil;
+(SqlHelper *)defaultSqlHelper{
    @synchronized(self){
        if (!helper) {
            helper = [[SqlHelper alloc]init];
            [self creatDataBaseWithTab];//创建数据库
        }
    }
    return helper;
}

+(void)creatDataBaseWithTab{
    FMDatabase *  fmdb = [FMDatabase databaseWithPath:[self getPath]];
    if (!fmdb) {
        NSLog(@"数据库已经创建或者已经存在");
    }
}
+(NSString *)getPath{
    return [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject] stringByAppendingPathComponent:@"DataBase1006.sqlite"];
}
@end
View Code SqlHelper文件

上面代码中,对于收藏功能没有完成,用本地数据库存储暂时没有实现

 

posted @ 2015-10-06 09:35  ywda  阅读(288)  评论(0编辑  收藏  举报