UITableView和UIRefreshControl

时间:2012-10-01 12:24:42

标签: uitableview uirefreshcontrol

我正在尝试将UIRefreshControl移到我的headerView之上,或者至少让它与contentInset一起使用。有谁知道如何使用它?

在TableView中滚动时,我使用了headerView来获得漂亮的背景。我想要一个可滚动的背景。

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// Set up the edit and add buttons.

self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
self.tableView.backgroundColor = [UIColor clearColor];

[self setWantsFullScreenLayout:YES];

self.tableView.contentInset = UIEdgeInsetsMake(-420, 0, -420, 0);

UIImageView *top = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"top.jpg"]];
self.tableView.tableHeaderView = top;

UIImageView *bottom = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bottom.jpg"]];
self.tableView.tableFooterView = bottom;

UIBarButtonItem *leftButton = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"settingsIcon"] style:UIBarButtonItemStylePlain target:self action:@selector(showSettings)];
self.navigationItem.leftBarButtonItem = leftButton;

UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addList)];
self.navigationItem.rightBarButtonItem = addButton;

//Refresh Controls
self.refreshControl = [[UIRefreshControl alloc] init];

[self.refreshControl addTarget:self action:@selector(refreshInvoked:forState:) forControlEvents:UIControlEventValueChanged];
}

2 个答案:

答案 0 :(得分:32)

我不太确定你对contentInset的意图是什么,但是在向UITableView添加UIRefreshControl方面,它可以完成。 UIRefreshControl实际上是用于UITableViewController,但如果你只是将它作为子视图添加到UITableView它就会神奇地起作用。请注意,这是未记录的行为,可能在其他iOS版本中不受支持,但它是合法的,因为它不使用私有API。

- (void)viewDidLoad
{
    ...
    UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
    [refreshControl addTarget:self action:@selector(handleRefresh:) forControlEvents:UIControlEventValueChanged];
    [self.myTableView addSubview:refreshControl];
}

- (void)handleRefresh:(id)sender
{
    // do your refresh here...
}

归功于@Keller for noticing this

答案 1 :(得分:10)

@ Echelon的回答很明显,但我有一个小建议。将刷新控件添加为@property,以便以后可以访问它。

在YourViewController.h中

@property (nonatomic, strong) UIRefreshControl *refreshControl;
在YourViewController.m

-(void) viewDidLoad {
    self.refreshControl = [[UIRefreshControl alloc] init];
    [self.refreshControl addTarget:self action:@selector(refresh) forControlEvents:UIControlEventValueChanged];
    [self.tableView addSubview:self.refreshControl]; //assumes tableView is @property
}

这样做的重要原因......

-(void)refresh {
    [self doSomeTask]; //calls [taskDone] when finished
}

-(void)taskDone {
    [self.refreshControl endRefreshing];
}

只是为您提供对UIRefreshControl的全班访问权限,以便您可以endRefreshing或检查UIRefreshControl的isRefreshing属性。