我有一个UIImageView作为我的表视图的背景视图。当表没有数据时,我将添加UILabel作为图像视图的子视图。我无法让标签居中。标签总是在右边。
UIImageView *backgroundImageView = [[UIImageView alloc]initWithFrame:self.tableView.frame];
backgroundImageView.image = [UIImage imageNamed:@"background"];
backgroundImageView.center = self.tableView.center;
self.noLocationsLabel = [[UILabel alloc]initWithFrame:backgroundImageView.frame];
self.noLocationsLabel.center = backgroundImageView.center;
self.noLocationsLabel.text = @"No saved locations";
self.noLocationsLabel.textAlignment = NSTextAlignmentCenter;
self.noLocationsLabel.textColor = [UIColor blackColor];
self.noLocationsLabel.font = [UIFont fontWithName:@"Chalkboard SE" size:24.0];
self.tableView.backgroundView = backgroundImageView;
if (self.locationsArray.count == 0) {
self.navigationItem.rightBarButtonItem.enabled = NO;
[self.tableView.backgroundView addSubview:self.noLocationsLabel];
self.tableView.userInteractionEnabled = NO;
}
答案 0 :(得分:1)
如果您的图像框架是50,50,50,50,那么您的标签也将是50,50,50,50,但由于它是图像视图的子视图,因此它永远不会位于中心。同样的概念适用于center
。中心仅针对观点超级视图。
为了使其居中,您可以将框架设置为:
CGRect rect = CGRectMake(0,0,backgroundImageView.frame.size.width,backgroundImageView.frame.size.height);
self.noLocationsLabel = [[UILabel alloc]initWithFrame: rect];
或者甚至可能:
self.noLocationsLabel = [[UILabel alloc]initWithFrame: backgroundImageView.bounds];
编辑:
您可以在子视图上使用center
。但你必须设置正确的中心。
self.noLocationsLabel.center = CGPointMake(CGRectGetMidX(backgroundImageView.bounds),CGRectGetMidY(backgroundImageView.bounds));