如何从Non ViewController类启动ViewController?

时间:2014-07-10 08:47:34

标签: ios objective-c

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

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

但是在这个特定的类上,自定义的UICollectionView单元格我希望根据单击的单元格启动一个新的控制器。我怎么能这样做?

7 个答案:

答案 0 :(得分:2)

您希望向细胞添加详细信息视图尝试Adding Detail Views上的此链接。希望此帮助

答案 1 :(得分:1)

通常的方法是在包含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];

}

答案 2 :(得分:1)

使用UICollectionViewDelegate method didSelectItemAtIndexPath执行此操作,并确保在实现UICollectionView的视图控制器类中存在此委托方法。

答案 3 :(得分:0)

您必须在单击单击时通知ViewController,其中存在UICollectionView。在此控制器上,您可以按下所需的控制器

答案 4 :(得分:0)

你需要一种推送或展示的视图控制器,没有办法解决这个问题。

你不应该在完成这个问题时遇到问题,并且有几种方法可以做到这一点。首先,您应该能够在UICollectionViewDelegate方法collectionView:didSelectItemAtIndexPath:中编写此逻辑。您的代理很可能是包含视图控制器,因此您可能只需要执行此操作。但是,如果它不是,只需向您的代理添加一个视图控制器属性,您可以使用它来呈现内容。使其成为弱点以避免可能的保留周期(视图控制器保留委托并且委托保留视图控制器)。

答案 5 :(得分:0)

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

现在你拥有它。

答案 6 :(得分:0)

您需要获取当前的UIViewController,有多种方法可以实现。您可以在UICollectionViewCell的头文件中解析VC。您也可以使用 self.window.rootviewcontroller

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

相关问题