简体   繁体   中英

I want to change the view controller when a button it's pressed iphone

I have a table view controller with custom cells. In those cells i added a button for each one of the cells. What i would like it's that when I press that button it display a new view with more information about that cell, different of the view that i get from didSelectRowAtIndexPath.

I know it's now a hard question. I've seen that the button has some action on interfacebuilder (touch down maybe) but how do i link it to what code. where should i declare the code that handle that event?

I've posted in other forums with no answer, hope this would work.

Thanks. Gian

I would probably subclass UIButton to have an instance of NSIndexPath. That way, each individual UIButton in a UITableViewCell can "know" where it is in the table view, so when you press the button, you can call some method that takes an NSIndexPath and pushes a new view, similar to what you do in -didSelectRowAtIndexPath: but with your other view instead (maybe give it a descriptive method name like -didPressButtonAtIndexPath: ).

Instead of using the Interface Builder to do this, you should add a method to the UIButton subclass itself that in turn calls a method on your view controller. Then, for each UIButton, you can use the UIControl method -addTarget:action:forControlEvents: . Have the UIButton call its own method, which calls the controller's method. Your solution might look something like:

// MyButton.h
@interface MyButton : UIButton {
    NSIndexPath *myIndexPath;
    MyViewController *viewController;
}

- (void)didPressButton;
@end

// MyViewController.h
@interface MyViewController { }
- (void)didPressButtonAtIndexPath:(NSIndexPath *)indexPath;
@end

Then, when you build your cells, for each button you add call:

[button addTarget:button 
           action:@selector(didPressButton)
 forControlEvents:UIControlEventTouchDown];

And finally, implement -didPressButton to look like:

- (void)didPressButton {
   [controller didPressButtonAtIndexPath:myIndexPath];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM