用于UITableViewCell的backgroundView的初始帧

我目前正在使用self.frame初始化我的UITableViewCell的backgroundView框架。 这似乎适用于设备方向更改(单元格背景填充整个单元格,看起来很好等)。 什么是更好的框架使用(如果有的话)?

编辑#1 :我还用CGRectZero初始化了backgroundView作为框架。 这似乎没有区别(UITableViewCells和backgroundViewsfunction在所有界面方向都很好)。

我还测试了设置autoresizingMask属性。 这没有任何区别。 我只想了解backgroundViews初始帧会影响什么(如果有的话)。

假设您正在尝试将UIImageView添加为backgroundView并且您正尝试调整该imageView的大小,这是我的经验:

似乎无法改变UITableViewCell.backgroundView的框架(或者至少不是Apple推荐的东西,因此在文档中没有提到)。 要使用自定义大小的UIImageView,例如使用可resize的UIImage,作为UITableViewCell中的背景,我执行以下操作:

1)创建一个UIImageView并将其image属性设置为您希望的图像。

2)使用addSubview:消息将UIImageView添加为UITableViewCell的子视图。

3)使用sendSubviewToBack:消息将UIImageView发送到后面。

这将您的UIImageView置于任何其他添加的子视图后面,您现在可以操纵“backgroundView”(也称为imageview)的框架。

要确保imageview适合tableViewCell的框架,请在计算imageview的高度时使用cell.frame的高度和宽度属性。

如果您开发自定义表格视图单元格,解决方案是在layoutSubviews方法中调整框架。 这是我的一个项目的自定义UITableViewCell,我需要从左边10点边距:

 #import "TETopicCell.h" #import "UIColor+Utils.h" @implementation TETopicCell @synthesize topicTitleLabel = _topicTitleLabel; - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; if (self) { UIImageView *bgImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"theme_btn_yellow"]]; bgImageView.contentMode = UIViewContentModeTopLeft; bgImageView.frame = CGRectMake(0.0f, 0.0f, 239.0f, 42.0f); self.backgroundView = bgImageView; _topicTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(46.0f, 0.0f, 206.0f, 42.0f)]; _topicTitleLabel.backgroundColor = [UIColor clearColor]; _topicTitleLabel.textColor = [UIColor colorWithR:116 G:74 B:1]; [self.contentView addSubview:_topicTitleLabel]; } return self; } - (void)layoutSubviews { [super layoutSubviews]; // update frame here self.backgroundView.frame = CGRectOffset(self.backgroundView.frame, 10.0f, 0.0f); // and here if (self.selectedBackgroundView){ self.selectedBackgroundView.frame = CGRectOffset(self.selectedBackgroundView.frame, 10.0f, 0.0f); } } - (void)setSelected:(BOOL)selected animated:(BOOL)animated { [super setSelected:selected animated:animated]; if (selected) { UIImageView *selectedImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"theme_btn_red"]]; selectedImageView.contentMode = UIViewContentModeTopLeft; selectedImageView.frame = CGRectMake(0.0f, 0.0f, 239.0f, 42.0f); self.selectedBackgroundView = selectedImageView; [_topicTitleLabel setTextColor:[UIColor colorWithR:255 G:211 B:211]]; } else { self.selectedBackgroundView = nil; [_topicTitleLabel setTextColor:[UIColor colorWithR:116 G:74 B:1]]; } } @end