2016-03-17 48 views
0

我想動態地將UILabel添加到我的UITableViewCell。所以在CellforrowAtIndex事件中我確實喜歡這樣。以編程方式將UILabel添加到UITableView無法正確加載

static NSString *simpleTableIdentifier = @"SimpleTableCell"; 
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier]; 
UILabel *lbl; 
[[cell viewWithTag:100] removeFromSuperview]; 

if (cell == nil) { 
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:simpleTableIdentifier]; 



} 

lbl=[[UILabel alloc] initWithFrame:cell.imageView.frame]; 
[lbl setText:[NSString stringWithFormat:@"%lu",[[[mutArrayPendingRequests objectAtIndex:indexPath.row] objectForKey:@"RequestItems"] count]]]; 
[lbl setTag:100]; 
[lbl setTextAlignment:NSTextAlignmentCenter]; 
[cell.contentView addSubview:lbl]; 

但我的問題是,當表加載我的文字沒有設置爲UILabel。但一旦我滾動它加載頂部3個單元格和底部3個單元格。中間單元格標籤不加載。這是什麼原因?我如何將一個UILabel作爲自定義視圖添加到我的UITableViewCell中? 請幫幫我。 感謝

+0

刪除此行'[[細胞viewWithTag:100] removeFromSuperview];'和嘗試 –

+0

然後其overwritting標籤值 – user1960169

回答

0

幀大小要爲其設置的標籤,即cell.imageView.frame是無效的。

設置一些適當的幀值,並檢查它會工作。

lbl=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 20)]; 
1

試試這個

if (cell == nil){ 
     cell = [[UITableViewCell alloc] 
         initWithStyle:UITableViewCellStyleDefault 
         reuseIdentifier: simpleTableIdentifier]; 

     //create custom labels and button inside the cell view 

     lbl = [[UILabel alloc] initWithFrame:cell.imageView.frame]; 
     lbl.tag = 100; 
     lbl.font = [UIFont boldSystemFontOfSize:17.0]; 
     lbl.backgroundColor = [UIColor clearColor]; 
     [lbl setTextAlignment:NSTextAlignmentCenter]; 
     [cell.contentView addSubview: lbl]; 
    } 
    else { 
     lbl = (UILabel *)[cell.contentView viewWithTag:100]; 
     } 

    [lbl setText:[NSString stringWithFormat:@"%lu",[[[mutArrayPendingRequests objectAtIndex:indexPath.row] objectForKey:@"RequestItems"] count]]]; 
0

嘗試此代碼:

static NSString *simpleTableIdentifier = @"SimpleTableCell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier]; 
    UILabel *lbl; 
    [[cell viewWithTag:100] removeFromSuperview]; 

    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:simpleTableIdentifier]; 

    } 


    lbl = [[UILabel alloc]initWithFrame:CGRectMake(0, 0,200 ,40)]; 
    [lbl setText:[NSString stringWithFormat:@"%lu",[[[mutArrayPendingRequests objectAtIndex:indexPath.row] objectForKey:@"RequestItems"] count]]]; 
    [lbl setTextAlignment:NSTextAlignmentCenter];   

    [cell.contentView addSubview:lbl]; 
    return cell; 
} 
相關問題