2016-04-13 111 views
-1

我有自定義單元格與一個按鈕的紅色與標題驗證和點擊它改變爲綠色與標題Experience.But問題是我滾動未點擊按鍵都轉變爲綠色色彩搭配題經驗桌面視圖自定義單元格按鈕顏色和標題更改在桌面視圖上的滾動

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

    static NSString *CellIdentifier = @"Cell1"; 



    BoastsMainCell1 *cell1 = 
    (BoastsMainCell1*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 






    cell1.selectionStyle = UITableViewCellSelectionStyleNone; 

    if(cell1 == nil) { 
     cell1 = [[BoastsMainCell1 alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 


    } 


    [cell1.verifyBnt addTarget:self action:@selector(verifyButtonClicked:) forControlEvents:UIControlEventTouchUpInside]; 

return cell1; 
} 



-(void)verifyButtonClicked:(UIButton*)sender 
{ 




    [sender setTitle:@"Experience" forState:UIControlStateNormal]; 
    sender.backgroundColor=[UIColor greenColor]; 




} 

回答

0

在您的BoastsMainCell1類中,您應該覆蓋- (void)prepareForReuse。正在發生的事情是操作系統正在重複使用一個單元,您應該重置其屬性。 prepareForReuse是您重新設置的機會。

From Apple's documentation:

如果一個UITableViewCell對象是可重複使用的,也就是說,它有一個再利用對象從UITableView的方法dequeueReusableCellWithIdentifier返回 之前 標識符調用此方法:.對於 性能原因,您應該只重置 與內容無關的單元格的屬性,例如alpha,編輯和選擇 狀態。 tableView:cellForRowAtIndexPath: 中的表視圖委託應該在重用單元時始終重置所有內容。如果單元格 對象沒有關聯的重用標識符,則此方法爲 未調用。如果您重寫此方法,則必須確保調用超類實現。

在實現文件中,BoastsMainCell1.m,你可以添加一個類似的方法:

- (void)prepareForReuse { 
     [super prepareForReuse]; 
     self.backgroundColor = [UIColor redColor]; 
    } 
+0

新蜜蜂可以üPLZ添加一些示例代碼 – salman4siddiquistackoverflow

+0

[超prepareForReuse]其給出的錯誤 – salman4siddiquistackoverflow

+0

沒有可見的接口聲明選擇器.. ?? – salman4siddiquistackoverflow

0

應重置電池狀態如下圖所示:

if(cell1 == nil) { 
     cell1 = [[BoastsMainCell1 alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
    } 
//it's just a example. some code like this to reset the UI element. 
// [cell1.verifyBnt setSelected:NO]; 
// [cell1 updateCell..... 

的原因是,該小區將被重用。

+0

我試過這個沒有結果 – salman4siddiquistackoverflow

+0

滾動表視圖m得到問題 – salman4siddiquistackoverflow

+0

@ salman4siddiquistackoverflow你沒有得到我的意思。在我的答案中的代碼後,你應該添加一些代碼來重置單元格。因爲這個單元格會被重用。您應該使用數據來記錄單元狀態,並且在單元將被重用時,根據單元狀態更改單元。 – user2027712

0

你有一個誤區,認爲,一個TableViewCell將保留其觀點的狀態。但它絕對錯誤。也就是說,TableViewCell將在您滾動tableview時重用,重用單元格將使用默認的UI狀態。在你的情況下,你必須保持按鈕的「選定」狀態,在單元格之外,就像ViewController類中的Dictionary。例如,當您從按鈕中獲取事件時,將該狀態存儲在字典中。而在「的cellForRowAtIndexPath」的方法,你必須檢查當前行是否已經從該字典選擇的狀態,並設置適當的顏色值,比如,

if (dict[@(indexPath.row)] == @(YES)) { 
    //Set red color 
} else { 
    //green color 
} 

需要注意的是,這可能不是最完美的方式。唯一的意圖是讓你明白如何細胞將被重用,以及你應該如何保存細胞狀態。

相關問題