以编程方式自动调整包含多个子视图的UITableViewCell

时间:2010-10-25 06:36:06

标签: objective-c ipad uitableview

我有一个 UITableView ,它看起来像一个网格:我通过添加 UILabel **作为** cell.contentView 子视图来模仿四列。 其中三个“列”具有固定的宽度,并且在旋转时我想自动调整最左边的列以填充所有可用空间(屏幕宽度减去其他三列的总宽度)。

单元格初始化代码如下:

#define kCellWidth ((UIInterfaceOrientationIsLandscape(self.interfaceOrientation)) ? 1024 : 768)
#define kCellHeight 60

#define kXOffset 10
#define kYOffset 10
#define kContentHeight (kCellHeight - 2*kYOffset)

#define kTypeWidth  125
#define kNumberWidth 100
#define kDateWidth  90
#define kLabelWidth  (kCellWidth - (2*kXOffset + kTypeWidth + kNumberWidth + kDateWidth))

#define kTypeOffset  (kXOffset + kLabelWidth)
#define kNumberOffset (kTypeOffset + kTypeWidth)
#define kDateOffset  (kNumberOffset + kNumberWidth)

#define kLabelTag 1
#define kTypeTag 2
#define kNumberTag 3
#define kDateTag 4

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier];

 if (cell == nil) {
  cell = [self cellWithFrame:CGRectMake(0, 0, kCellWidth, kCellHeight)
      identifier:kCellIdentifier];
 }

 Clazz *obj = [self.source objectAtIndex:indexPath.row];
 ((UILabel *) [cell viewWithTag:kLabelTag]).text  = obj.label;
 ((UILabel *) [cell viewWithTag:kTypeTag]).text  = obj.type;
 ((UILabel *) [cell viewWithTag:kNumberTag]).text = obj.number;
 ((UILabel *) [cell viewWithTag:kDateTag]).text  = obj.date;

 return cell;
}

-(UITableViewCell *) cellWithFrame:(CGRect)frame identifier:(NSString *)identifier {
 UITableViewCell *cell = [[[UITableViewCell alloc] initWithFrame:frame
               reuseIdentifier:kCellIdentifier] autorelease];

 [cell.contentView addSubview:[self labelForTag:kLabelTag
           withFrame:CGRectMake(kXOffset, kYOffset, kLabelWidth, kContentHeight)]];
 [cell.contentView addSubview:[self labelForTag:kTypeTag
           withFrame:CGRectMake(kTypeOffset, kYOffset, kTypeWidth, kContentHeight)]];
 [cell.contentView addSubview:[self labelForTag:kNumberTag
           withFrame:CGRectMake(kNumberOffset, kYOffset, kNumberWidth, kContentHeight)]];
 [cell.contentView addSubview:[self labelForTag:kDateTag
           withFrame:CGRectMake(kDateOffset, kYOffset, kDateWidth, kContentHeight)]];

 return cell;
}

-(UILabel *)labelForTag:(int)tag withFrame:(CGRect)frame {
 UILabel *label = [[UILabel alloc] initWithFrame:frame];
 label.tag = tag;

 switch (tag) {
  case kNumberTag:
  case kDateTag:
   label.textAlignment = UITextAlignmentCenter;
   break;
  default:
   break;
 }

 return [label autorelease];
}

问题是:

  • 我可以通过使用autoresizingMask和 - 或contentMode属性来实现这种行为吗?
  • 如果是,我应该更改哪些对象的属性以及哪些值?

我已经尝试了一下,但由于我是一名iPad编程新手,因此无法找到解决方案。提前谢谢!

1 个答案:

答案 0 :(得分:0)

    CGRect frame = self.tableView.frame;
    CGFloat height1=120.0;
    [tableView setRowHeight:height1];
    self.tableView.frame = frame; 

这样您就可以通过编程方式设置rowheight