我正在尝试创建一个从 XIB 加载自定义单元格的 UITableView。我有 EventsCell.xib 以及 .m 和 .h 文件。
单元格的内容和高度是动态的,因为它可以包含未知数量的子视图。
这是加载单元格的代码。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"EventsCellIdentifier";
EventsCell *cell = (EventsCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"EventsCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
NSDictionary *hour = [[[eventsArray objectAtIndex:[indexPath section]] valueForKey:@"hours"] objectAtIndex:[indexPath row]];
NSArray *events = [hour valueForKey:@"events"];
cell.events = events;
cell.timeLabel.text = [hour valueForKey:@"name"];
int offset = 0;
for(NSDictionary *event in events)
{
UIView *vvv = [[UIView alloc] initWithFrame:CGRectMake(50, offset, 270, 44)];
[vvv setBackgroundColor:[UIColor clearColor]];
UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 44)];
lab.text = [event valueForKey:@"name"];
lab.backgroundColor = [UIColor clearColor];
[vvv addSubview:lab];
[cell.contentView addSubview:vvv];
offset += 44;
}
return cell;
}
它加载单元格,但在我在表格视图上滚动几次后,内容如下所示:
我究竟做错了什么?..
谢谢!
==================== 更新====================
现在另一件事正在发生。我已经在单独的视图控制器中添加了添加到单元格的子视图的所有元素。像下面这样。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"EventsCellIdentifier";
EventsCell *cell = (EventsCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"EventsCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
for (UIView *subV in [cell.contentView subviews]){
[subV removeFromSuperview];
}
NSDictionary *hour = [[[eventsArray objectAtIndex:[indexPath section]] valueForKey:@"hours"] objectAtIndex:[indexPath row]];
NSArray *events = [hour valueForKey:@"events"];
cell.events = events;
cell.timeLabel.text = [hour valueForKey:@"name"];
int offset = 0;
for(NSDictionary *event in events)
{
EventBoxViewController *ebvc = [[EventBoxViewController alloc] initWithNibName:@"EventBoxViewController" bundle:nil];
ebvc.nameLabel.text = [event valueForKey:@"name"];
[ebvc.view setFrame:CGRectMake(50, offset, 270, 44)];
[cell.contentView addSubview:ebvc.view];
offset += 44;
}
return cell;
}
而且它们没有按应有的方式加载。请看下图。
它们仅在我滚动浏览单元格时才加载,即使那样它们也不会按应有的方式加载。标签的文本也没有被分配。关于我做错了什么的任何想法?
谢谢你。