2010-02-13 41 views
2

我創建了一個UITableView每個電池行的按鈕。該按鈕用作開關,將所選行添加爲NSUserDefaults中的「最愛」。我的問題是,每當我按下這個按鈕時,就會在舊的按鈕上繪製一個新的按鈕。我如何釋放/重用它? 這是我cellForRowAtIndexPath方法是什麼樣子:iPhone動態的UIButton中的UITableView

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

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease]; 
     cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; 

    } 

    UIImage *favOn = [UIImage imageNamed:@"favOn.png"]; 
    UIImage *favOff = [UIImage imageNamed:@"favOff.png"];     
    UIButton *favButton = [[UIButton alloc] initWithFrame:CGRectMake(230, 0, 54, 54)]; 


    favButton.tag = viewTag; 

    [favButton setImage:favOff forState:UIControlStateNormal]; 
    [favButton setImage:favOn forState:UIControlStateSelected]; 

    if([self getFavState:viewTag]) { 

     [favButton setSelected:YES]; 
    } 
    else { 
     [favButton setSelected:NO]; 
    } 

    [favButton addTarget:self action:@selector(favButtonSwitch:) forControlEvents:UIControlEventTouchUpInside]; 
    [favButton setBackgroundColor:[UIColor clearColor]]; 
    [cell.contentView addSubview:favButton]; 
    [favButton release]; 

    return cell; 
} 

而且我用三種不同方法爲按鈕的選擇:

- (void) setFavState:(BOOL)state withId:(NSString *)uid { 

    NSUserDefaults *savedData = [NSUserDefaults standardUserDefaults]; 
    [savedData setBool:state forKey:uid]; 
} 

- (BOOL) getFavState:(NSString *)uid { 

    NSUserDefaults *savedData = [NSUserDefaults standardUserDefaults]; 
    return [savedData boolForKey:uid]; 
} 

- (void) favButtonSwitch:(id) sender { 
    NSInteger senderId = [sender tag]; 
    NSString *senderString = [NSString stringWithFormat:@"%i", senderId]; 

    NSLog(@"sender:%i",senderId); 

    [self getFavState:senderString]; 

    if([self getFavState:senderString]) { 

     [self setFavState:NO withId:senderString]; 
    } 
    else { 
     [self setFavState:YES withId:senderString]; 
    } 

    [self.tableView reloadData]; 
} 

回答

1

你似乎每次要創建新圖像的新按鈕即使它是從緩存中檢索出來的,也可以是。將用於創建帶有圖像的按鈕的代碼移動到第一次創建單元的代碼中。

if (cell == nil) { 
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease]; 
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; 
    // Move all the image and button creation in here... 
} 
+0

謝謝,這只是部分工作,因爲它不會在點擊/單擊按鈕時直觀地更新選擇狀態。我看到它確實是由senderId激活,但沒有立即選擇/未選擇uicontrol狀態(,因爲它是那麼從以前開始緩存?) – scud 2010-02-13 21:37:54

+0

那麼你需要把代碼設置按鈕的狀態外塊,然後。那有意義嗎?也許現在重新發布你的代碼? – willcodejavaforfood 2010-02-13 23:02:31

+0

我現在修好了,我最大的錯誤是按鈕切換方法中的[self.tableView reloadData]。我用這樣一個真正的開關替換它:if([sender isSelected])... [sender setSelected:NO] – scud 2010-02-13 23:15:24

相關問題