Reputation: 13
I want to display a UILabel and a UIButton in my app, when the table is empty. However, it's only showing the label. I know that's because I'm only adding the label to the view. How do I add the button to the view as well?
UILabel *messageLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
messageLabel.text = @"No data is currently available. Please pull down to refresh.";
messageLabel.textColor = [UIColor blackColor];
messageLabel.numberOfLines = 0;
messageLabel.textAlignment = NSTextAlignmentCenter;
messageLabel.font = [UIFont fontWithName:@"Palatino-Italic" size:20];
[messageLabel sizeToFit];
UIButton *messageButton = [UIButton buttonWithType:UIButtonTypeSystem];
[messageButton addTarget:self
action:@selector(aMethod:)
forControlEvents:UIControlEventTouchUpInside];
[messageButton setTitle:@"Add your first service"
forState:UIControlStateNormal];
messageButton.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[self.tableView addSubview:messageButton];
[self.tableView addSubview:messageLabel];
self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
Upvotes: 0
Views: 108
Reputation: 38239
Best is to use viewForHeaderInSection
method of UITableView
as your requirment is to use only when empty data so it will be displayed when its empty and removed automatically when has data
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
if([yourTblViewDataArray count] == 0)
{
//Add UILabel and UIButton in UIView
UIView *view = [[UIView alloc] init];
//here
return view;
}
else
{
return nil;
}
}
HeightForHeaderInSection
of UITableView
which is necessary should be added:
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
//According to requirement size should vary
if([yourTblViewDataArray count] == 0)
{
return 60.0f;
}
else
{
return 0.0f;
}
}
Upvotes: 0
Reputation: 7948
You haven't added messageButton to any view (or not in the code you have shown).
You need something like:
[self.tableView addSubview:messageButton];
[self.tableView addSubview:messageLabel];
Upvotes: 1
Reputation: 41
Instead of using a tableViewController you can use a normal viewController and add a tableview in it. Also add button and label in interface. Then set these item to hidden or not based on the elements of the tableview.
Upvotes: 0
Reputation: 89509
What you should be doing is dropping your UILabel and UIButton into your XIB or Storyboard, whatever holds the table view, connecting them to outlets and then hiding or showing them depending on if the table has any entries or not.
But yes, Nick's answer is also correct (and +1 to him). Instead of doing "self.tableView.backgroundView
", you should be doing "[self.tableView addSubview:messageButton];
".
Upvotes: 2