如何从UIView的子类中推出视图控制器

4
我创建了一个名为"CategoryTableView"的视图,它是从UIView子类化而来。并且CategoryTableView包含一个UITableView。我将CategoryTableView作为子视图添加到从UIViewController子类化而来的HomeViewController中。现在,当didSelectRowAtIndexPath执行时,我想要推送一个新的视图控制器。但是,在CategoryTableView中,我该如何推送或呈现另一个视图控制器?我无法进入CategoryTableView中的导航控制器。

你不需要这样做。重新设计你的代码。 - user529758
完成。我正在使用委托,并且现在可以推到新的视图控制器。 - yong ho
2个回答

7

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;

如果parentViewController在UINavigationController的堆栈中,则代码有效。 - Tirth
谢谢,它也起作用了。你的方法比我计划使用委托方法更好。 - yong ho
3
这种写法虽然可行,但是不好的做法。UIView不应该直接访问导航控制器,因为这会破坏MVC模式。破坏MVC并不意味着代码会失败,但它意味着你最终会得到一段混乱的代码,每个类都不清楚其职责,对于大型项目而言,代码将变得难以理解。UIView应该只是一个视图,负责呈现视觉效果,而不控制任何应用逻辑。这是控制器的职责。因此,你应该将你的UIViewController设为委托对象,从UIView接收消息并执行导航逻辑。 - Leo Flaherty

2

您需要使用自定义委托来实现这一点...

CategoryTableView.h

@protocol CategoryTableViewDelegate <NSObject>

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

@end

@interface CategoryTableView : UIView

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

@end

CategoryTableView.m 文件中:
实现 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

HomeViewController.h文件中。
 @interface HomeViewController : UIViewController <CategoryTableViewDelegate>

    @end

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];
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接