如何从Non ViewController类启动ViewController?

标题说这一切,我通常打开ViewControllers像这样

ListingViewController *listingView = [[ListingViewController alloc]init]; [self.navigationController pushViewController:listingView animated:YES]; 

但在这个特定的类多数民众赞成在一个自定义的UICollectionView单元我想启动一个新的控制器基于单元格点击。 我怎样才能做到这一点 ?

通常的方法是在包含UICollectionView的视图控制器中实现UICollectionViewDelegate方法– collectionView:didSelectItemAtIndexPath: :。 然后你可以以正常的方式呈现新的视图控制器。

例如:

 - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath { [collectionView deselectItemAtIndexPath:indexPath animated:YES]; MyModel * model = self.listItems[indexPath.row]; //retrieve the object that is displayed by the cell at the selected index MyViewerViewController * vc = [[MyViewerViewController alloc] initWithMyModel:model]; [self.navigationController pushViewController:vc animated:YES]; } 

您正在寻找添加详细信息视图到单元格尝试此链接添加详细视图 .Hopefully这有助于

使用UICollectionViewDelegate方法didSelectItemAtIndexPath来做到这一点,并确保这个委托方法存在于实现UICollectionView的视图控制器类中。

您必须在单元格单击时通知ViewController存在哪个UICollectionView。 并在这个控制器上,你可以推动所需的控制器

你需要一个视图控制器来推动或呈现,这是没有办法的。

你不应该有一个问题完成,有几种方法可以做到这一点。 首先,您应该能够在UICollectionViewDelegate方法collectionView:didSelectItemAtIndexPath:编写此逻辑。 你的委托最有可能是包含的视图控制器,所以你可能需要做的。 但是,如果不是,只需将视图控制器属性添加到您的委托,您可以用于显示的东西。 使它成为一个弱的,以避免可能的保留周期(视图控制器保留委托,委托保留视图控制器)。

self.navigationController只能通过UIViewController的子类访问。 你想从UIViewcontroller类访问UINavigationController。 你在问什么?

如果你有像AppDelegate那样的UINavigationController属性

 @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @property (strong, nonatomic) UINavigationController *navigationController; @end 

你可以从任何地方得到一个指针,如下所示

 #import "AppDelegate.h" AppDelegate *delegate = (AppDelegate *)[[[UIApplication sharedApplication] delegate]; UINavigationController *navigation = [delegate navigationController]; 

现在你拥有了。

你需要获得当前的UIViewController,有多种方式来做到这一点。 你可以在你的UICollectionViewCell头文件中parsingVC。 你也可以使用self.window.rootviewcontroller

之后,你可以使用[VC pushViewController:listingView animated:YES]; 或[self.window.rootviewcontroller pushViewController:listingView animated:YES];