2011-06-20 37 views
1

我遇到了當前應用程序的問題。它在UIViewController中有一個UITableView。我在底部有一個UIButton(出UITableView)。它的工作原理是這樣:2 NSArrays在一個UITableView標籤作爲子視圖?

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

static NSString *ident = @"indet"; 

cell = [tableView dequeueReusableCellWithIdentifier:ident]; 
if (cell == nil) { 
    cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:ident] autorelease]; 

} 

if (![[NSUserDefaults standardUserDefaults] boolForKey:@"bla"]) { 

cell.textLabel.text = [firstArray objectAtIndex:indexPath.row]; 

} else { 

cell.textLabel.text = [secondArray objectAtIndex:indexPath.row]; 

}     
return cell; } 

現在我想用一個UILabel代替cell.textLabel,因爲我需要它的一些原因:

if ([[NSUserDefaults standardUserDefaults] boolForKey:@"bla"]) { 
[[NSUserDefaults standardUserDefaults] setBool:FALSE forKey:@"bla"]; 
[tableView reloadData]; 
} else { 

[[NSUserDefaults standardUserDefaults] setBool:TRUE forKey:@"tasks2do"]; 
[tableView reloadData]; } 

,當我有這樣的cell.textLabel.text方法這個工作(例如,設置標籤幀)

對於我用下面的代碼:

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

static NSString *ident = @"indet"; 

cell = [tableView dequeueReusableCellWithIdentifier:ident]; 
if (cell == nil) { 
    cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:ident] autorelease]; 
} 
UILabel *thislabel = [[[UILabel alloc] initWithFrame:CGRectMake(10, 10, 250, 44)] autorelease]; 

if (![[NSUserDefaults standardUserDefaults] boolForKey:@"bla"]) { 

    [thislabel setText:[firstArray objectAtIndex:indexPath.row]]; 

    } else { 

    [thislabel setText:[secondArray objectAtIndex:indexPath.row]]; 

} 

[cell.contentView addSubview:thislabel]; 

return cell; } 

這工作正常,直到我推UIButton切換。它切換,電池顯示新文本,但背後的新文本仍然是舊的文本,你可以在這裏看到:

http://d.pr/Rqx2

(該firstArray包含字母L時,secondArray包含字母J,它混合起來)

你有任何想法解決這個問題,因爲我嘗試了一些東西(例如使用2 UILabel s的數組和隱藏一個)?會很酷。 :)

我希望我的英語不是太難理解,我的寫作英語技能不是最好的,我很抱歉。

如果您需要更多信息/代碼,請將其發佈,不應該成爲問題。

回答

0

我建議您創建一個UITableViewCell子類,在其中配置標籤(設置框架並將其作爲子視圖添加到UITableViewCell的初始化程序中)。添加屬性設置標籤中的文字,寫一個二傳手喜歡本作的屬性:

- (void)setLabelText:(NSString *)newLabelText 
{ 
    if ([self.labelText isEqualToString:newLabelText]) return; 
    [labelText autorelease]; 
    labelText = [newLabelText copy]; 

    self.label.text = labelText; 
    [self.label setNeedsDisplay]; // or perhaps [self setNeedsDisplay]; 
} 

編輯:順便說,你正在處理的問題是緩存。每當單元格出現時,都會重新創建一個新標籤,即使單元格之前已經有了標籤。發生這種情況是因爲您在UITableViewCell初始化程序之外初始化一個UILabel(每個緩存單元只應調用一次,之後可從緩存中檢索它,包括所有它的子視圖)。

+0

嗨,感謝您的回覆,我想解決與緩存問題。我該如何解決這個問題?移動UILabel * bla = [[UILabel alloc] init ...]; in:if(cell == nil){cell [= [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:ident] autorelease]; }?感謝您的進一步解答! – Nicolai

+0

是的,應該修復它,但是您不會在初始化程序之外引用自定義標籤。所以我建議你製作這個小類。 –

+0

好吧,我測試了它:它沒有修復,TableView會變得瘋狂,文本在滾動時發生變化。你能否更詳細地解釋你的子類方法?我沒那麼有經驗。 :( – Nicolai

相關問題