仿今日头条新闻上下拉刷新

一.实现业务处理层

// 创建单利方法

+ (instancetype)shareLoadData;

// 创建解析方法

- (void)getContent:(NSString *)url;

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

实现方法

// 创建单利变量
static LoadData *ld;
@implementation LoadData
{
    __block NSMutableDictionary *ContentDic,*ContentDic1;
}
// 创建单利方法
+ (instancetype)shareLoadData{
    //
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        ld = [[LoadData alloc]init];
    });
    return ld;
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone{
    if (!ld) {
        ld = [super allocWithZone:zone];
    }
    return ld;
}
- (id)copy{
    return self;
}
- (id)mutableCopy{
    return self;
}
// 解析方法
- (void)getContent:(NSString *)url{
    NSURLSession *session = [NSURLSession sharedSession];
   
    NSURLSessionTask *task = [session dataTaskWithURL:[NSURL URLWithString:url] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        // 用系统自带的JSON解析
        self->ContentDic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        // 回到主线程发送通知
        dispatch_async(dispatch_get_main_queue(), ^{
            [[NSNotificationCenter defaultCenter]postNotificationName:@"getContent" object:self->ContentDic];
        });
    }];
    [task resume];
}
@end

二.实现自定义cell

// 创建三个控件

@property(nonatomic,strong)UILabel *titleLb,*timeLb;

@property(nonatomic,strong)UIImageView *img;

// 实现这三个控件

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{

    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];

    if (self) {

        [self addSubview:self.titleLb];

        [self addSubview:self.timeLb];

        [self addSubview:self.img];

    }

    return self;

}

- (UILabel *)titleLb{

    if (!_titleLb) {

        // 初始化位置

        _titleLb = [[UILabel alloc]initWithFrame:CGRectMake(10, 20,240, 100)];

        // 设置自动换行

        _titleLb.numberOfLines = 0;

        // 设置背景颜色

        // _titleLb.backgroundColor = [UIColor greenColor];

        // 设置字体大小

        _titleLb.font = [UIFont systemFontOfSize:22];

    }

    return _titleLb;

}

- (UIImageView *)img{

    if (!_img) {

        // 初始化位置

        _img = [[UIImageView alloc]initWithFrame:CGRectMake(260,10,120,120)];

        // 设置背景颜色

        _img.backgroundColor = [UIColor yellowColor];

    }

    return _img;

}

- (UILabel *)timeLb{

    if (!_timeLb) {

        // 初始化位置

        _timeLb = [[UILabel alloc]initWithFrame:CGRectMake(240,130,195,40)];

        // 设置背景颜色

//        _timeLb.backgroundColor = [UIColor blueColor];

        // 设置字体大小

        _timeLb.font = [UIFont systemFontOfSize:16];

    }

    return _timeLb;

}

三.在ViewController控制器中添加

#import "ViewController.h"

#import "UIImageView+WebCache.h"

#import "LoadData.h"

#import "MyTableViewCell.h"

#import "MJRefresh.h"

#import "MJRefreshHeader.h"

#import "MJRefreshAutoFooter.h"

#import "MBProgressHUD.h"@interface ViewController (){

    // 创建全局表格

    UITableView *_tableView;

    // 创建字典用于接收

    NSDictionary *_ContentDic;

    // 创建数组用于获取字典中的数组

    NSArray *_ContentArray;

    // 定义网址

    NSURL *_PathUrl;

    // 定义变量

    int *num;

}

@end

@implementation ViewController

- (void)viewDidLoad {

    [super viewDidLoad];

    num = 3;

    // 注册通知

    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getContent:) name:@"getContent" object:nil];

    // 初始化表格

    _tableView = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];

    // 设置代理

    _tableView.delegate = self;

    _tableView.dataSource = self;

    // 添加到主视图

    [self.view addSubview:_tableView];


    // 调用业务处理层方法

    [self Load];


    // 创建下拉刷新控件

    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(MJHeader)];

    _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMore)];

}

#pragma mark - 创建业务处理层方法

- (void)Load{

    // 每次刷新增加新闻数量

    num = num + 1;

    // 创建业务处理层对象

    LoadData *ld = [LoadData shareLoadData];

    NSString *TEXT_URL = [NSString stringWithFormat:@"https://way.jd.com/jisuapi/get?channel=头条&num=%d&start=0&appkey=54e619938bc38b40151c7bc35a29067e",num];

    // 将网址转换成UTF8格式传过去

    NSString *str = [TEXT_URL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    // 调用里面的方法

    [ld getContent:str];

}

#pragma mark - 发送通知接收方法

- (void)getContent:(NSNotification *)notifi{

    // 接收数据

    _ContentDic = notifi.object;


  // dic = [_ContentDic mutableCopy];

    // 刷新表格

    [_tableView reloadData];

}

#pragma mark - 下拉刷新控件方法

- (void)MJHeader{

    // 创建菊花加载控件

    MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];


    // 回到主线程刷新表格

    dispatch_async(dispatch_get_main_queue(), ^{

        // 刷新表格

        [self->_tableView reloadData];

        // 刷新时间

        [HUD setMinShowTime:1];

        // 一秒后隐藏

        [HUD hide:YES];

    });

    // 调用业务处理层方法

    [self Load];

    // 刷新

    [_tableView.mj_header endRefreshing];

}

#pragma mark - 上拉刷新控件方法

- (void)loadMore{

    // 调用业务处理层方法

    [self Load];

    // 刷新表格

    [_tableView reloadData];

    // 结束上拉刷新

    [_tableView.mj_footer endRefreshing];

}

#pragma mark - 表格数据源方法

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    // 用数组接收字典中的数据

    _ContentArray = _ContentDic[@"result"][@"result"][@"list"];

    // 返回数组中的个数

    return _ContentArray.count;

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString *str = @"cell";

    MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str];

    // 判断

    if (!cell) {

        // 创建cell

        cell = [[MyTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];

    }

    // 获取数组中的字典

    NSDictionary *dic = _ContentArray[indexPath.row];

    // 获取标题并赋值

    cell.titleLb.text = dic[@"title"];

    // 获取时间并赋值

    cell.timeLb.text = dic[@"time"];

    // 用SDWebImage第三方库加载图片

    NSString *URlStr = dic[@"pic"];

    _PathUrl = [NSURL URLWithString:URlStr];

    [cell.img sd_setImageWithURL:_PathUrl placeholderImage:[UIImage imageNamed:@"机器人.jpg"]];

    return cell;

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return 180;

}

@end

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 200,527评论 5 470
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,314评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 147,535评论 0 332
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,006评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,961评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,220评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,664评论 3 392
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,351评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,481评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,397评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,443评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,123评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,713评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,801评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,010评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,494评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,075评论 2 341

推荐阅读更多精彩内容