简体   繁体   中英

Display a label covering the whole UITableView

I'd like to display a big fat label overlayed on top of my UITableView if there are no elements to be displayed. (This label would provide instructions on how to add elements.) I wonder what the best method would be to achieve this.

I tried dragging a UIView on my UITableView. I thought I could add labels there and then set the .hidden property programmatically. However, it seems to be tricky to embed the UIView in the UITableView using IB.

Is it possible to create the label programmatically and have it cover a big chunk of my UITableView (ie, not just be in a particular cell of the table)?

There is no need to add a special overlay view for this purpose.

you can do this by assigning the created label to the property self.tableView.backgroundView in the numberOfSectionsInTableView method of the UITableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
  if (loans) { // check if the data is present or not

    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    return 1;

  } else { // if not present

    // Display a message when the table is empty
    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.";
    messageLabel.textColor = [UIColor blackColor];
    messageLabel.numberOfLines = 0;
    messageLabel.textAlignment = NSTextAlignmentCenter;
    messageLabel.font = [UIFont fontWithName:@"Palatino-Italic" size:20];//
    [messageLabel sizeToFit];

    self.tableView.backgroundView = messageLabel;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

  }

  return 0;
}

If you don't want to do it yourself: https://github.com/dzenbot/DZNEmptyDataSet

Otherwise create a label programmatically and add it like this:

let myLabel = UILabel(frame: myTableView.frame)
myLabel.text = "Hello World"
self.view.addSubview(myLabel)
myTableView.hidden = true

If you want to just provide insructions and then want to remove overlayed view or any.

  1. Create View

var DynamicView=UIView(frame: self.view.frame) DynamicView.alpha = 0.5 self.view.addSubview(DynamicView)

  1. Add Label to DynamicView at position where you want....

  2. Add tapGesture to dismiss/hide view.

var tapGesture = UITapGestureRecognizer(target: self, action: "tapDetected") self. DynamicView.alpha.addGestureRecognizer(tapGesture)

create "tapDetected" method and write code to hide DynamicView

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM