UITableview中怎麼找到每個cell,UITableviewcell

來源:互聯網
上載者:User

UITableview中怎麼找到每個cell,UITableviewcell

一個朋友問我:我在每個cell中都添加了兩個按鈕(記為btnA和btnB),點擊btnA時,對應的cell中添加一個子控制項,再點擊btnB時,對應的cell中的子控制項就移除,怎麼做到?

 

百度了一下,發現瞭解決辦法:

首先,建立btn時,給每個btn加一個tag值

//建立cell方法-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{    static NSString * iden=@"iden";    _cell=[tableView dequeueReusableCellWithIdentifier:iden];    if (_cell==nil) {        _cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:iden];    }        UIButton * btnA=[UIButton buttonWithType:UIButtonTypeCustom];    btnA.frame=CGRectMake(0, 0, 50, 20);    btnA.tag = 1000 + indexPath.row;    btnA.backgroundColor=[UIColor greenColor];    [btnA addTarget:self action:@selector(btnBClick:) forControlEvents:UIControlEventTouchUpInside];        [_cell.contentView addSubview:btnA];        UIButton * btnB=[UIButton buttonWithType:UIButtonTypeCustom];    btnB.tag = 2000 + indexPath.row;    btnB.frame=CGRectMake(100, 0, 50, 20);    btnB.backgroundColor=[UIColor redColor];    [btnB addTarget:self action:@selector(btnAClick:) forControlEvents:UIControlEventTouchUpInside];    [_cell.contentView addSubview:btnB];    return _cell;}
 1 //添加子控制項按鈕代碼 2 -(void)btnBClick:(UIButton *)btn 3 { 4     NSString * path=[[NSBundle mainBundle]pathForResource:@"1" ofType:@"mp4"]; 5     NSURL * url=[NSURL fileURLWithPath:path]; 6     _mp=[[MPMoviePlayerViewController alloc]initWithContentURL:url]; 7     _mp.view.backgroundColor=[UIColor purpleColor]; 8     _mp.moviePlayer.controlStyle=MPMovieControlStyleDefault; 9     10     _mp.view.frame=CGRectMake(0, 0, self.view.frame.size.width, 200);11     NSIndexPath *indexPath = [NSIndexPath indexPathForRow:btn.tag - 1000 inSection:0];12     UITableViewCell *cell = [_tableView cellForRowAtIndexPath:indexPath];// 竟然還有這個方法,第一次用13     [cell.contentView addSubview:_mp.view];14     [_tableView reloadData];15 }
 1 //移除子控制項按鈕代碼 2 -(void)btnAClick:(UIButton *)btn 3 { 4     NSIndexPath *indexPath = [NSIndexPath indexPathForRow:btn.tag - 2000 inSection:0]; 5     UITableViewCell *cell = [_tableView cellForRowAtIndexPath:indexPath]; 6     if ([cell.contentView.subviews containsObject:_mp.view]) { 7         [_mp.view removeFromSuperview]; 8     } 9     else10         return;11 }

給添加了紅色的幾行代碼,就搞定了!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.