How to Find each cell in UITableview, UITableviewcell
A friend asked me: I added two buttons (marked as btnA and btnB) to each cell. When you click btnA, add a child control to the corresponding cell and click btnB, the child control in the corresponding cell is removed. How can this problem be solved?
Baidu found a solution:
First, add a tag value to each btn when creating btn.
// Create the cell method-(UITableViewCell *) tableView :( UITableView *) tableView cellForRowAtIndexPath :( NSIndexPath *) indexPath {static NSString * iden = @ "iden"; _ cell = [tableView progress: iden]; if (_ cell = nil) {_ cell = [[UITableViewCell alloc] initWithStyle: Invalid reuseIdentifier: iden];} UIButton * btnA = [UIButton buttonWithType: callback]; 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 // Code 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]; // you can use this method for the first time: 13 [cell. contentView addSubview: _ mp. view]; 14 [_ tableView reloadData]; 15}
1 // Code 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}
Just add several lines of red code!