2013-05-06 73 views
2

我有一個可重複使用的電池在我的UITableView,我想只在特定的細胞添加自定義圖像。自定義子視圖添加到某些reusablecells在UITableView的

這裏是我的示例代碼:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    BCContactCell * cell = [tableView dequeueReusableCellWithIdentifier:contactCellIdentifier]; 
    ... 
    if ([contact isFavorite]) { 
     UIImageView * fav = [[UIImageView alloc] initWithFrame:CGRectMake(280.0f, 2.0f, 32.0f, 32.0f)]; 
     [fav setImage:favoriteImg]; // already loaded 
     [cell addSubview:fav]; 
    } 
} 

它的工作原理,以及每一個喜愛的接觸在其細胞中的圖片。 除了向下滑動時,其他細胞也開始拍照,我似乎無法弄清楚。

任何人都可以幫助我如何做到這一點?

謝謝!

回答

6

在這裏,我們走了,

給一個標籤號到您的ImageView, fav.tag = 1290; 後來用這個數字我們可以得到舊的UIImageView回來,並從細胞中移除。
否則{ [[細胞viewWithTag:1290] removeFromSuperview]; }

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    BCContactCell * cell = [tableView dequeueReusableCellWithIdentifier:contactCellIdentifier]; 
    ... 
    if ([contact isFavorite]) { 
     UIImageView * fav = [[UIImageView alloc] initWithFrame:CGRectMake(280.0f, 2.0f, 32.0f, 32.0f)]; 
     fav.tag = 1290; 
     [fav setImage:favoriteImg]; // already loaded 
     [cell addSubview:fav]; 
    }else{ 
     [[cell viewWithTag:1290] removeFromSuperview]; 
    } 
} 

當談到UITableViewCells,他們重用已創建的細胞。當他們重用舊的一次。您必須刪除添加到單元格中的UIImageView;

+0

這解決了我的問題。 Thx爲快速回答和解釋。 – DCMaxxx 2013-05-06 15:47:14

+0

你忘了,你是重用細胞 - 這意味着每次當你從調用[的tableView dequeueReusableCellWithIdentifier:contactCellIdentifier]已使用的電池,要複製的圖片。在重複使用的單元格中,圖片可能已經作爲子視圖添加 - 但無論如何您正在添加一個新的。你應該實現一個檢查,如果imageview已經存在,如果是 - 不要創建一個新的。還要注意刪除圖像 - 如果帶有標籤1290的imageview不可用,則對viewWithTag的調用將返回nil,然後您不能調用removeFrom Superview – smat88dd 2014-07-24 23:10:15

相關問題