简体   繁体   中英

Detecting From which Cell , UIButton was pressed in a UITableView

I have two custom UItableViewCell with Same UIButton , How to determine from Which Cell UIButton is called ?

PS I Don't want To use two different methods.

cellForRowAtIndexPath Method.

if (indexPath.row==1) {
static NSString *cellIdentifier = @“CustomeCell1“;

                            NewsFeedCell1 *cell = (NewsFeedCell1 *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
cell.btnPrivacy.tag = indexPath.row;
[cell.btnPrivacy addTarget:self action:@selector(btnPrivacyClicked:) forControlEvents:UIControlEventTouchUpInside];

}
else
{
static NSString *cellIdentifier = @"CustomeCell2”;

                            NewsFeedCell2 *cell = (NewsFeedCell2 *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
cell.btnPrivacy.tag = indexPath.row;
[cell.btnPrivacy addTarget:self action:@selector(btnPrivacyClicked:) forControlEvents:UIControlEventTouchUpInside];

}

Button click Methods.

-(IBAction)btnPrivacyClicked:(UIButton *)sender
{
    NSLog(@"Privacy Clicked at : %ld",(long)sender.tag);

    // Here Determine From Which Cell UiButton Is Clicked.
    NewsFeedCell1 *cell = (NewsFeedCell1 *)[self.HomeTable cellForRowAtIndexPath:[NSIndexPath indexPathForRow:sender.tag inSection:0]];
// *** Use Following code to detect `Cell` ***
CGPoint buttonPosition = [button convertPoint:CGPointZero toView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];
[self.tableView cellForRowAtIndexPath:indexPath];

Set tag for cell.btnPrivacy.tag=indexPath.row;

and in button action you will get button btnPrivacy tag ie sender.tag which is cell index.

Try with this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM