zoukankan      html  css  js  c++  java
  • objc_setAssociatedObject获取cell上button对应所在的行

    #import <UIKit/UIKit.h>
    
    @interface TestCell : UITableViewCell
    @property (weak, nonatomic) IBOutlet UIButton *btnTest;
    
    @end
    #import "ViewController.h"
    #import "TestCell.h"
    #import <objc/runtime.h>
    
    static void *btnIndexPathKey = "btnIndexPathKey";
    @interface ViewController ()<UITableViewDataSource,UITableViewDelegate>
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
    }
    
    - (void)didReceiveMemoryWarning {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }
    
    
    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
    {
        return 1;
    }
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
        return 5;
    }
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        TestCell *test = [tableView dequeueReusableCellWithIdentifier:@"TestCell" forIndexPath:indexPath];
        /**设置cell上button的关联对象*/
        objc_setAssociatedObject(test.btnTest, btnIndexPathKey, indexPath, OBJC_ASSOCIATION_ASSIGN);
        return test;
    }
    - (IBAction)btnClick:(UIButton *)sender
    {
        /**获取对应关联对象的值*/
        NSIndexPath *btnIndexPath = objc_getAssociatedObject(sender, btnIndexPathKey);
        NSLog(@"btnIndexPath.row = %ld",btnIndexPath.row);
        
    }

  • 相关阅读:
    构建之法阅读心得(九)
    构建之法阅读心得(八)
    构建之法阅读心得(七)
    构建之法阅读心得(六)
    构建之法阅读心得(五)
    构建之法阅读心得(四)
    一组阶段小记之读构建之法(三)
    暑期学习总结
    软工综合实践 学习笔记02
    软工综合实践 学习笔记01
  • 原文地址:https://www.cnblogs.com/thbbsky/p/4653522.html
Copyright © 2011-2022 走看看