UITableViewCell覆盖:在cellForRowAtIndexPath中分配UILabel时?

时间:2014-07-07 10:28:22

标签: ios uitableview

我想在UITableviewCell文件中显示nib。并且还想在其上添加动态标签。但标签是否超越自我。 请提供任何方法,我可以从UITableviewCell拨打nib并添加动态标签。

- (void)viewDidLoad
{
  [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

UINib *nib = [UINib nibWithNibName:@"ItemCell" bundle:nil];
[[self tblView] registerNib:nib forCellReuseIdentifier:@"ItemCell"];

}

- (void)didReceiveMemoryWarning
 {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
 }


#pragma mark

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  return 1;
   }

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section                {
return 4;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath  *)indexPath {

 return 150.0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

ItemCell *cell =  [tableView dequeueReusableCellWithIdentifier:@"ItemCell"];

    for (int i=0; i<4; i++) {
    UILabel *lbl=[[UILabel alloc] initWithFrame:CGRectMake(0.0, 20.0*i, 150.0, 20.0)];
    lbl.text=@"This is custom cell.";
    [cell.contentView addSubview:lbl];
    }

return cell;
}

2 个答案:

答案 0 :(得分:1)

使用此

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath   *)indexPath 
{
UILabel *lbl; 
ItemCell *cell = (ItemCell *)[tableView dequeueReusableCellWithIdentifier:@"ItemCell"];
if (cell == nil)
{
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ItemCell" owner:self options:nil];
    cell = [nib objectAtIndex:0];
    lbl=[[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 150.0, 60.0)];
    lbl.tag = indexpath.row; 
    [cell.contentView addSubview:lbl];
} 
lbl = (UIlabel*) [cell.contentView viewWithTag:indexpath.row]; 
lbl.text=@"This is custom cell.";
return cell;
}

答案 1 :(得分:1)

试试这个

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

 ItemCell *cell =  [tableView dequeueReusableCellWithIdentifier:@"ItemCell"];

 UILabel* label = (UILabel*)[cell.containtView viewWithTag:indexPath.row];
 if(!label) {
   UILabel *lbl=[[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 150.0, 60.0)];
   lbl.text=@"This is custom cell.";
   lbl.tag = indexPath.row
   [cell.contentView addSubview:lbl];
 }
 label.text = @"your text";
 return cell;
}