Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
763 views
in Technique[技术] by (71.8m points)

objective c - iOS - passing arguments in action:@selector()

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, where rowNum is the row that the button appears in.

When adding the target to the button, Xcode autocompletes the following:

[buttonDown addTarget:self action:@selector(quantityDown:rowNumber:) forControlEvents:UIControlEventTouchUpInside];

But no matter what I try, I cannot pass the row number into the method. I assumed the pertinent portion of code would look like

action:@selector(quantityDown:rowNumber:indexPath.row)

but that doesn't do the trick. I've seen other stuff like

action:@selector(quantityDown:)rowNumber:indexPath.row

and

action:@selector(quantityDown:rowNumber:)withObject:@"first" withObject:@"Second"

But neither work. I don't need to pass a first argument, just the row number. I've also tried defining the method like - (void) quantityDown:(int)rowNum and then writing the selector like:

action:@selector(quantityDown:indexPath.row)

but that also doesn't work.

Thoughts?

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...