In general UIViews
should not contain any logic that triggers the flow of app. This is the job of UIViewControllers
. It's just a way of making the design of your code better and more organized.
One way I often use is to use a delegate
pattern in my custom UIViews. Here is s simple setup:
In your MyCustomView .h file:
@class MyCustomView;
@protocol MyCustomViewDelegate <NSObject>
@optional
- (void)myViewDidTapOnButton:(MyCustomView)myCustomView;
@end
@interface MyCustomView : UIView
@property (weak, nonatomic) id <MyCustomViewDelegate> delegate;
@end
In your MyCustomView .m file:
- (IBAction)didTapMyButton:(id)sender {
if ([self.delegate respondsToSelector:@selector(myViewDidTapOnButton:)]) {
[self.delegate myViewDidTapOnButton:self];
}
}
Then in your viewcontroller, which is presenting your view:
interface:
@interface MyViewController ()<MyCustomViewDelegate>
@property (weak, nonatomic) IBOutlet UIView *myCustomView;
and implementation:
- (void)viewDidLoad {
[super viewDidLoad];
self.myCustomView.delegate = self;
}
- (void)myViewDidTapOnButton:(MyCustomView)myCustomView {
... code for presenting viewcontroller ...
}
Note:
Even if you dont use the parameter myCustomView
which is sent in this method, its a common pattern and good habit to always send the sender
of the delegate as the first parameter.
This is also used a lot by Apple, e.g. in
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;