2014-02-17 22 views
0

自定義單元格的標籤中的文本將顯示一個塊。有沒有更好的方法來完成這一點?iOS7:UILabel自定義單元格中的文本不會在沒有GCD的情況下出現

CustomCell.h

@interface CustomCell : UITableViewCell 
@property (nonatomic, strong) UILabel *label; 
@property (nonatomic, strong) UIView *circle; 
@end 

CustomCell.m

@implementation CustomCell 
- (void)layoutSubviews 
{ 
    [super layoutSubviews]; 
    self.circle = [[UIView alloc] initWithFrame:CGRectMake(10, 10, 40.0f, 40.0f)]; 
    [self.circle setBackgroundColor:[UIColor brownColor]; 

    self.label = [[UILabel alloc] initWithFrame:CGRectMake(15, 20, 200.0f, 50.0f)]; 
    self.label.textColor = [UIColor blackColor]; 

    [self.contentView addSubview:self.label]; 
    [self.contentView addSubview:self.circle]; 

//I have also tried [self addSubview:self.label]; 

} 

tableView.m

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *customCellIdentifier = @"CustomCell"; 

    CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:customCellIdentifier]; 
    if (cell == nil) { 
     cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:inviteCellIdentifier]; 
    } 

    dispatch_async(dispatch_get_main_queue(), ^{ 
    [[cell label] setText:@"This is Label"]; 
    [cell setNeedsDisplay]; 
}); 
    return cell; 
} 

我可以得到的UILabel來顯示文本的唯一方法是,使用嵌段以上。如果我不使用該塊,只需使用cell.Label.text = @"This is a Label"後跟[cell setNeedsDisplay];,文本就不會出現,我必須滾動tableview才能重新加載單元格,並且只有標籤中的文本纔會出現。

有沒有更好的方法,還是我堅持不得不使用該塊?

回答

2

你不爲label屬性創建UILabel直到電池的layoutSubviews方法被調用這是很久以後你嘗試設置標籤的文本在表格視圖控制器。

移動到自定義單元格的initWithStyle:reuseIdentifier:方法創建標籤。也可以撥打self.contentView addSubview:init...方法。唯一應該在layoutSubviews方法中的是標籤框架的設置。

一旦你這樣做,你將不再需要在cellForRow...方法使用GCD的。

做了circle財產一樣了。

順便說一句 - 你使用GCD解決了這個問題,因爲它給單元格改變了它的layoutSubviews方法來調用,創建標籤。

+0

我正在嘗試此操作。謝謝。 – user1107173

+0

我是否在layoutsubviews中初始化並設置了框架?或者在iniwithstyle中初始化並在layoutsubviews中設置框架? – user1107173

+1

在你調用'self.label = [[UILabel alloc] initWithFrame:...];''和'[self.contentView addSubview:self.label]'的'init ...'方法中,以及設置其他標籤屬性。 'layoutSubviews'只需要根據需要調整框架。 – rmaddy

0

首先,您不應該在layoutSubviews中分配和放置視圖。應該在創建單元格時創建和放置視圖,並且只在layoutSubviews方法中更改框架(如果需要)。否則,你會得到相互重疊的噸重複的意見。

接下來,你不應該使用dispatch_async的tableView內:的cellForRowAtIndexPath :.您可以直接設置文本標籤。你也不應該需要setNeedsDisplay,因爲無論如何系統都會對新的單元格做這些事情。

相關問題