我有一个带有自定义类的 UIImageView。当按下图像时,类应该推送一个新的 View Controller ,但是我似乎无法获得对当前 UINavigationController 的引用。我通常会做 self.navigationController,但在这里我不能。 我尝试了以下代码,但它不起作用:
[self.window.rootViewController.navigationController pushViewController:browser animated:YES];
最佳答案
给你的自定义 ImageView 一个委托(delegate):
@protocol CustomImageViewDelegate;
@interface CustomImageView : UIImageView
@property (weak, nonatomic) id<CustomImageViewDelegate> delegate;
@end
@protocol CustomImageViewDelegate
- (void)imageViewPressed:(CustomImageView *)imageView
@end
使您的 View Controller 成为委托(delegate)。按下图像时,您执行 [self.delegate imageViewPressed:self
。
您的 View Controller 将实现:
- (void)imageViewPressed:(CustomImageView *)imageView
{
[self.navigationController pushViewController:browser animated:YES];
}
或者给你的 View 一个 Navigation Controller 属性:
@interface CustomImageView : UIImageView
@property (weak, nonatomic) UINavigationController navigationController;
@end
然后您可以直接在自定义 ImageView 上使用[self.navigationController pushViewController:browser animated:YES]
。
您必须设置 navigationController
属性,iOS 不会为您做这件事。
在你的 Controller 上添加一行
self.yourCustomImageViewProperty.navigationController = self.navigationController;
这是一个非常基本的回答,但我希望它能引导您朝着正确的方向前进。
关于ios - 从 UIImageView 类访问 UINavigationViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23726338/