iOS - passing arguments in action:@selector()

后端 未结 3 1535
臣服心动
臣服心动 2020-12-18 11:12

I\'m adding a button to a UITableViewCell programmatically. The method to be run when the button is pressed is - (void) quantityDown:(id)sender rowNumber:(int)rowNum<

3条回答
  •  臣服心动
    2020-12-18 12:06

    Why don't you make a Custom UIButton class and have the object as property?

    See below.

    "MyButton.h"

    @interface MyButton : UIButton
    @property(nonatomic, strong)MyClass *obj;
    @end
    

    "MyButton.m"

    #import "MyButton.h"
    
    @implementation MyButton
    
    - (id)initWithFrame:(CGRect)frame
    {
        self = [super initWithFrame:frame];
        if (self) {
            // Initialization code
        }
        return self;
    }
    
    @end
    

    Now assign MyButton class to your actual button in the cell/ or initialize the custom button instead of normal UIButton class and assign the object directly.

    And in your IBAction where sender=MyButton

    - (void) quantityDown:(id)sender{
       MyButton *btn  = (MyButton *)sender;
       //You get the object directly
       btn.obj;
    }
    

    Doing it this way you can actually access as many properties you want easily. And its useful in other implementations too.

    Hope it helps.

提交回复
热议问题