Reputation: 2063
I am adding a UILabel and UIActivityIndicatorView as a subview to a tableview as a loading indicator. I want these items to be in the middle of the visible are of the table view, and remain in the center if the user scrolled, so the user will always see the items. My code to create them is:
if (!spinner) {
spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[spinner startAnimating];
loadingLabel = [[UILabel alloc] initWithFrame:CGRectZero];
loadingLabel.font = [UIFont systemFontOfSize:20];
loadingLabel.textColor = [UIColor grayColor];
loadingLabel.text = @"Loading...";
[loadingLabel sizeToFit];
static CGFloat bufferWidth = 8.0;
CGFloat totalWidth = spinner.frame.size.width + bufferWidth + loadingLabel.frame.size.width;
CGRect spinnerFrame = spinner.frame;
spinnerFrame.origin.x = (self.tableView.bounds.size.width - totalWidth) / 2.0;
spinnerFrame.origin.y = (self.tableView.bounds.size.height - spinnerFrame.size.height) / 2.0;
spinner.frame = spinnerFrame;
spinner.autoresizingMask = (UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin);
[self.tableView addSubview:spinner];
CGRect labelFrame = loadingLabel.frame;
labelFrame.origin.x = (self.tableView.bounds.size.width - totalWidth) / 2.0 + spinnerFrame.size.width + bufferWidth;
labelFrame.origin.y = (self.tableView.bounds.size.height - labelFrame.size.height) / 2.0;
loadingLabel.frame = labelFrame;
loadingLabel.autoresizingMask = (UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin);
[self.tableView addSubview:loadingLabel];
}
How can I make it recenter when the table view scrolls?
EDIT
How would I calculate the sizes to reposition the spinner to the middle? What property would I set?
Upvotes: 1
Views: 2880
Reputation: 958
Add your view to the superview of the table view (if possible; UITableViewController
makes this impossible)
Add your view to the table view and reposition it in the -scrollViewDidScroll:
delegate method (UITableViewDelegate
is a sub-protocol of UIScrollViewDelegate
)
EDIT:
For maintaining center of the view
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
CGSize adSize = [awView actualAdSize];
CGRect newFrame = awView.frame; newFrame.origin.x = (self.view.bounds.size.width - adSize.width)/2;
newFrame.origin.y = (self.tableView.contentOffset.y - adSize.height/2) -21;
awView.frame = newFrame;
}
Upvotes: 2