如何使用Refresh Control刷新TableViewCell数据

时间:2017-04-17 20:11:59

标签: ios objective-c

每当激活刷新控件时,我都会尝试将数据加载到UITableViewCell。我的代码成功检索了数据,我可以使用NSLog验证这一点,但是当Refresh Control结束时,ViewCell不会使用新数据进行更新。有人能指出我正确的方向吗?

下面是MyViewController.m文件:

#define JSON_URL @"https://website.com"
#import "MyViewController.h"
#import "Object.h"
#import "MyViewCell.h"
@interface MyViewController ()


@property (nonatomic,strong) NSMutableArray *objectHolderArray;
@end

@implementation MyViewController
- (void)viewDidLoad
{

NSURL *blogURL = [NSURL URLWithString:JSON_URL];
NSData *jsonData = [NSData dataWithContentsOfURL:blogURL];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization
                                JSONObjectWithData:jsonData options:0 error:&error];
for (NSDictionary *bpDictionary in dataDictionary) {
    Object *currenHotel = [[Object alloc]Station:[bpDictionary objectForKey:@"station"] Status:[bpDictionary objectForKey:@"status"]];
    [self.objectHolderArray addObject:currenHotel];
}
[super viewDidLoad];

//to add the UIRefreshControl to UIView
UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:@"Please Wait..."]; //to give the attributedTitle
[refreshControl addTarget:self action:@selector(refresh:) forControlEvents:UIControlEventValueChanged];

}



- (IBAction)refresh:(UIRefreshControl *)sender {
    [self viewDidLoad];
    [sender endRefreshing];
}




#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:
(NSInteger)section
{
    return [self.objectHolderArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:
(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
MartaViewCell *cell = [tableView     dequeueReusableCellWithIdentifier:CellIdentifier
                                                  forIndexPath:indexPath];
Object *currentHotel = [self.objectHolderArray
                             objectAtIndex:indexPath.row];

cell.lblStation.text = currentHotel.station;
cell.lblStatus.text = currentHotel.status;
return cell;
}
-(NSMutableArray *)objectHolderArray{
if(!_objectHolderArray) _objectHolderArray = [[NSMutableArray alloc]init];
return _objectHolderArray;
}


@end

2 个答案:

答案 0 :(得分:2)

您需要重新加载数据。像这样实现Refreshcontroll:

 - (void)viewDidLoad {
    refreshControl = [[UIRefreshControl alloc] init];
    [refreshControl addTarget:self
                       action:@selector(update)
             forControlEvents:UIControlEventValueChanged];

    [self.startScreenView addSubview:refreshControl];
}

- (void) update {
     [refreshControl beginRefreshing];
     [yourTableView reloadData];
     [refreshControl endRefreshing];
 }

答案 1 :(得分:0)

您实际上不会在刷新功能中以任何方式修改或重新加载表视图及其数据。您应该更新表视图的数据源,然后在更新后调用[tableView reloadData];