IOS之表视图下拉刷新(免UITableViewController)

        我们要实现的效果如下:


IOS之表视图下拉刷新(免UITableViewController)

 

1.在头文件添加refreshControl变量

@property (nonatomic, strong) UIRefreshControl* refreshControl;

 2.在viewDidLoad添加初始化UIRefreshControl代码

 

//初始化UIRefreshControl
    UIRefreshControl *rc = [[UIRefreshControl alloc] init];
    rc.attributedTitle = [[NSAttributedString alloc]initWithString:@"下拉刷新"];
    [rc addTarget:self action:@selector(refreshTableView) forControlEvents:UIControlEventValueChanged];
    self.refreshControl = rc;
    [self.tableView addSubview:self.refreshControl];

 3.自定义刷新及刷新后的回调函数

-(void) refreshTableView
{
    if (self.refreshControl.refreshing) {
        self.refreshControl.attributedTitle = [[NSAttributedString alloc]initWithString:@"加载中..."];
        //添加新的模拟数据
        NSDate *date = [[NSDate alloc] init];
        //模拟请求完成之后,回调方法callBackMethod
        [self performSelector:@selector(callBackMethod:) withObject:date afterDelay:3];
    }
}

//这是一个模拟方法,请求完成之后,回调方法
-(void)callBackMethod:(id) obj
{
    [self.refreshControl endRefreshing];
    self.refreshControl.attributedTitle = [[NSAttributedString alloc]initWithString:@"下拉刷新"];
    NSMutableDictionary *newItem = [NSMutableDictionary dictionary];
    int randomNumber = arc4random() % 100 ;//[0,100)包括0,不包括100
    NSString* userName = [NSString stringWithFormat:@"user%d",randomNumber];
    [newItem setObject:userName forKey:@"itemName"];
    [newItem setObject:@"1.jpeg" forKey:@"itemImagePath"];
    [dataArr insertObject:newItem atIndex:0];
    
    [self.tableView reloadData];
}

 

你可能感兴趣的:(UITableView)