Detecting which UIButton was pressed in a UITableView

前端 未结 26 3379
小蘑菇
小蘑菇 2020-11-22 00:40

I have a UITableView with 5 UITableViewCells. Each cell contains a UIButton which is set up as follows:

- (UITableView         


        
26条回答
  •  情书的邮戳
    2020-11-22 00:44

    How about sending the information like NSIndexPath in the UIButton using runtime injection.

    1) You need runtime on the import

    2) add static constant

    3) add NSIndexPath to your button on runtime using:

    (void)setMetaData:(id)target withObject:(id)newObj

    4) on button press get metadata using:

    (id)metaData:(id)target

    Enjoy

        #import 
        static char const * const kMetaDic = "kMetaDic";
    
    
        #pragma mark - Getters / Setters
    
    - (id)metaData:(id)target {
        return objc_getAssociatedObject(target, kMetaDic);
    }
    
    - (void)setMetaData:(id)target withObject:(id)newObj {
        objc_setAssociatedObject(target, kMetaDic, newObj, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    
    
    
        #On the cell constructor
        - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
        {
        ....
        cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        ....
        [btnSocial addTarget:self
                                       action:@selector(openComments:)
                             forControlEvents:UIControlEventTouchUpInside];
    
        #add the indexpath here or another object
        [self setMetaData:btnSocial withObject:indexPath];
    
        ....
        }
    
    
    
        #The action after button been press:
    
        - (IBAction)openComments:(UIButton*)sender{
    
            NSIndexPath *indexPath = [self metaData:sender];
            NSLog(@"indexPath: %d", indexPath.row);
    
            //Reuse your indexpath Now
        }
    

提交回复
热议问题