使用约束给tableview添加暂无数据的提示
在tableview没有数据的时候,我们经常需要在tableview的正中间插入一张图片,来提示用户暂无数据
/** * 添加一个view,提示暂无数据 */ - (void)addPromptView { UIView* promptView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 150)]; UIImageView* promptImageView = [[UIImageView alloc] init]; CGFloat promptImageViewW = 107; CGFloat promptImageViewX = (promptView.frame.size.width - promptImageViewW) / 2; CGFloat promptImageViewY = 0; CGFloat promptImageViewH = 96; CGRect promptF = CGRectMake(promptImageViewX, promptImageViewY, promptImageViewW, promptImageViewH); promptImageView.frame = promptF; promptImageView.image = [UIImage imageNamed:@"暂无数据.png"]; promptImageView.contentMode = UIViewContentModeScaleAspectFit; promptView.center = self.view.center; [promptView addSubview:promptImageView]; self.promptView = promptView; self.promptView.hidden = YES; [self.tableView addSubview:self.promptView];
//添加约束,使promptView保持在tableview的正中间 [promptView setTranslatesAutoresizingMaskIntoConstraints:NO]; [self.tableView addConstraint:[NSLayoutConstraint constraintWithItem:promptView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.tableView attribute:NSLayoutAttributeCenterX multiplier:1.0f constant:0.0f]]; [self.tableView addConstraint:[NSLayoutConstraint constraintWithItem:promptView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.tableView attribute:NSLayoutAttributeCenterY multiplier:1.0f constant:0.0f]]; [self.tableView addConstraint:[NSLayoutConstraint constraintWithItem:promptView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:0.0f constant:[UIScreen mainScreen].bounds.size.width]]; [self.tableView addConstraint:[NSLayoutConstraint constraintWithItem:promptView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:0.0f constant:150.0f]]; }