很多朋友覺得UITableViewCell複用問題很難處理,百思不得其解,甚至有很多朋友自己琢磨很久也不明白個究竟。現在分享一下個人的一些經驗,希望對大家有幫助, 如果有好的意見或者有不同的看法也可以提出來,讓我們一起分享一起進步,知識只有在分享的情況下才能實現它的最大價值。好了,廢話少說,直奔主題了。列舉兩個場景 對比一下,也許tableviewcell的複用就很清晰明瞭了。 例1: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ static NSString *CellIdentifier = @"cell1"; UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; UILabel *labelTest = [UILabel alloc]init]; [labelTest setFrame:CGRectMake(2, 2, 80, 40)]; [labelTest setBackgroundColor:[UIColor clearColor]; [labelTest setTag:1]; [cell contentView]addSubview:labelTest]; } UILabel *label1 = (UILabel*)[cell viewWithTag:1]; [label1 setText:[self.tests objectAtIndex:indexPath.row]; return cell; } 例2: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath{ static NSString *CellIdentifier = @"cell1"; UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; } UILabel *labelTest = [UILabel alloc]init]; [labelTest setFrame:CGRectMake(2, 2, 80, 40)]; [labelTest setBackgroundColor:[UIColor clearColor]; //之所以這裏背景設爲透明,就是爲了後面讓大家看到cell上疊加的label。 [labelTest setTag:1]; [cell contentView]addSubview:labelTest]; [labelTest setText:[self.tests objectAtIndex:indexPath.row]; return cell; } 當你上下來回滑動tableview的時候就會看到區別,第一種程序界面不會出現異常,但是第二種就不是了,會出現字體疊加現象,其實更確切的是多個label的疊加。爲什 麼呢,因爲在tableview刷新的時候,如果那個位置已經有現成的cell,它就不會再重新請求資源生成新的cell了,而是複用原來的cell。所以對於對於第一種,代碼的思路 是第一次在cell不存在的時候生成cell,定義cell樣式,以後不管是刷新還是重新請求還好,它都只是複用已生成的cell。而第二種思路是,在cell不存在的時候,請求生成 cell,然後給cell上添加label,刷新的時候,會複用已有的cell,但是會重複添加label,故造成重疊的現象。 二 .UIbutton
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
中進行獲取這個tag值,獲取方法是:
UIButton *exitBtn = (UIButton *)[cell viewWithTag:1];//1是我上面設置的tag值
這樣就獲取到了,你再給他添加action事件就可以了,