關於cell中添加子視圖 復用重疊問題的解決方法


問題本質:  
因為你要添加的子視圖並不是在自定義的cell中實現的,而是根據系統給的UITableViewCell這個類創建的實例,每次進圖 cellForRow方法都會創建一個cell,每次都要創建一個子視圖添(button,label之類的)加進去,會給占用很大的內存,所以采用了復 用的方法,但是問題就來了,當cell超出界面,從隊列中拿過來復用的時候,其中子視圖的內容並沒有消除,這樣你會原來的基礎上再創建一個子視圖添加上去 遮住了原來的視圖,一般視圖都是透明的這樣的話就變成了一層層的疊加.

 

解決方法:

  下面給出得是一個label添加到cell中的例子

將具體的視圖實例,添加到cell的contentView中

注意:如何在父視圖中標識某個子視圖?

step1:在添加子視圖時,指定tag值(大於0)

step2:為了找出這個子視圖,通過調用父視圖的 viewWithTag 方法,就可以找到指定的視圖

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

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell1" ];

    if (cell==nil) {

        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"Cell1"];

    }

    //把索引給系統  forIndexPath:indexPath為注冊准備的,如果要自己創建的話,就把這個去掉

    // cell.detailTextLabel.text=@"detail.. ";

   // cell.imageView.image=[UIImage imageNamed:@"icon1.png"];

    

    //cell.textLabel.text=@"helo";

    //先按照tag值試着去Cell中找,是否有標簽

    UILabel  *label=(UILabel*)[cell.contentView viewWithTag:1];

    if (label==nil) {//如果沒找到再新建

        label=[[UILabel alloc]init];

       //為label設置tag值

        label.tag=1;

        label.textColor=[UIColor redColor];

        label.font=[UIFont italicSystemFontOfSize:40];

        label.frame=CGRectMake(0, 0, cell.bounds.size.width, 42);

        label.textAlignment=NSTextAlignmentCenter;

        [cell.contentView addSubview:label];

 

    }

     label.text=[NSString stringWithFormat:@"   %ld", indexPath.row];

        

    return cell;

}        


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM