Leo
Leo

Reputation: 492

Add UIButton to UITableView programmatically but the button doesn't show

I'd like to add a button above table view, not scrolled with the table view. But the button doesn't show. Any ideas?

UIButton *refreshButton = [UIButton buttonWithType:UIButtonTypeCustom];
[refreshButton setImage:[UIImage imageNamed:@"refresh"] forState:UIControlStateNormal];
CGRect applicationFrame = [UIScreen mainScreen].bounds;
CGFloat screenWidth = CGRectGetWidth(applicationFrame);
CGFloat screenHeight = CGRectGetHeight(applicationFrame);
CGFloat buttonWidth = 40.0f;
CGFloat buttonHeight = 40.0f;
CGFloat spacing = 10.0f;
CGFloat buttonX = screenWidth - buttonWidth - spacing;
CGFloat buttonY = screenHeight - buttonHeight - spacing;
CGRect buttonFrame = CGRectMake(buttonX, buttonY, buttonWidth, buttonHeight);
refreshButton.frame = buttonFrame;
[refreshButton addTarget:self
                  action:@selector(clickRefreshButton)
        forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:refreshButton];

Thanks in advance!

Upvotes: 0

Views: 454

Answers (1)

Mundi
Mundi

Reputation: 80265

You cannot do this with a UITableViewController. The reason: the view property of the view controller is the table view, so you cannot add anything above it.

The way to do this is to use a plain UIViewController and add your button and a UITableView as subviews (better in Interface Builder than in code, BTW).

In order to make the table view work as expected you have to add

  • an outlet for the table view
  • adopt the UITableViewDataSource and UITableViewDelegate protocols
  • as in a UITableViewController, implement at least the necessary datasource methods

Upvotes: 1

Related Questions