English 中文(简体)
iPhone table view - some button/action questions
原标题:

I created a table view that is populated with a custom UITableViewCell (like this). Each of the cells contains two UIButtons. I assign the action to the button like this:

 [decreaseButton addTarget:self action:@selector(decrease) forControlEvents:UIControlEventTouchUpInside];

Is this the right way? Anyway, it works, but in my "decrease" method I need to know in which of my 18 table view rows the button was pressed. indexPath.row doesn t work outside the cellForRowAtIndexPath method, of course. Can someone explain me how to do this?

Thanks a lot in advance!

iYassin

最佳回答

You can do this in two ways.

Inspecting the Event Sender

Change your decrease method from:

- (void)decrease;

to:

- (void)decrease:(id)sender;

That way when decrease is called, you ll be given a reference to the button that had the touch up inside event.

Define the decrease Method Closer to the Information

Another solution would be to have a different target instance for each button (for example, implement the decrease function as part of the custom cell). That way you know the button that was touched was the one for the current cell.

问题回答

The way i solved this is I keep track of data i might need inside my custom cell object. And the button is connected not to the external receiver but the cell it s self which in-turn knows how to call the real receiver of the action.

I make my cell with something like:

cell = [[MyTableViewCell alloc] initWithStyle:style 
                              reuseIdentifier:CellIdentifier];

And I have a setup method so i can re-init a cell when I dequeue it:

[cell setupMyCellWithContext:objectID 
                      target:[[UIApplication sharedApplication] delegate] 
                      action:@selector(someAction)];

so inside your cell class you use the action and target that was sent in the setup method to call the true target:

- (void)doAction:(id)sender {
    if ([target respondsToSelector:action]) {
        [target performSelector:action withObject:objectID afterDelay:0];
    }
}

So when your user taps the button, the os calls [cell doAction:], which calls the target and action selector you set up before hand with the correct context object.





相关问题
Code sign Error

I have created a new iPhone application.I have two mach machines. I have created the certificate for running application in iPhone in one mac. Can I use the other mac for running the application in ...

ABPersonViewController Usage for displaying contact

Created a View based Project and added a contact to the AddressBook using ABAddressBookRef,ABRecordRef now i wanted to display the added contact ABPersonViewController is the method but how to use in ...

将音频Clips从Peter改为服务器

我不禁要问,那里是否有任何实例表明从Peit向服务器发送音响。 I m不关心电话或SIP风格的解决办法,只是一个简单的袖珍流程......

• 如何将搜查线重新定位?

我正试图把图像放在搜索条左边。 但是,问题始于这里,搜索条线不能重新布署。

热门标签