how to push view controller from a UIView's subclass

丶灬走出姿态 提交于 2019-12-19 09:16:41

问题


I created a view "CategoryTableView" that subclass from UIView. And CategoryTableView contains a UITableView. I added CategoryTableView as a subview to HomeViewController that subclass from UIViewController. Right now, I want to push a new view controller when didSelectRowAtIndexPath executes. But, in CategoryTableView, how do I push or present another view controller. I can't get to the navigation controller in CategoryTableView.


回答1:


CategoryTableView.h

@property (retain, nonatomic) parentViewController *parent; //create one property for parent view like this

CategoryTableView.m

@sythesize parent;

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [parent.navigationController . . .]; // preform action
    //OR..
    [parent presentModalViewController: . . .]; // present modal view
}

parent.m

//while calling your CategoryTableView assign self to your parent object

    CategoryTableView *tblView = [CategoryTableView alloc] init];
    tblView.parent = self;



回答2:


You need to use custom delegates to achieve this...

in CategoryTableView.h

@protocol CategoryTableViewDelegate <NSObject>

-(void)pushViewControllerUsinDelegate:(UIViewController *)viewController;

@end

@interface CategoryTableView : UIView

@property (nonatomic, retain) id<CategoryTableViewDelegate> delegate;

@end

in CategoryTableView.m

@implementation CategoryTableView

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //Create the required UIViewControllers instance and call the delegate method.
    UIViewController *viewController = [[UIViewController alloc] init];
    [self.delegate pushViewControllerUsinDelegate:viewController];
}


@end

in HomeViewController.h

 @interface HomeViewController : UIViewController <CategoryTableViewDelegate>

    @end

in HomeViewController.m

@implementation HomeViewController

-(void)viewDidLoad
{
    [super viewDidLoad];

    //initialization of CategoryTableView like this...
    CategoryTableView *categoryTableViewInstance = [[CategoryTableView alloc] init];
    [categoryTableViewInstance setDelegate:self];

}

-(void)pushViewControllerUsinDelegate:(UIViewController *)viewController
{
    [self.navigationController pushViewController:viewController animated:YES];
}


来源:https://stackoverflow.com/questions/15779485/how-to-push-view-controller-from-a-uiviews-subclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!