从UIView到UIViewController? [英] Get to UIViewController from UIView?

查看:73
本文介绍了从UIView到UIViewController?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一个内置的方法从 UIView 到它的 UIViewController ?我知道你可以从 UIViewController 到它的 UIView 通过 [self view] 但我想知道是否有一个反向引用?

Is there a built-in way to get from a UIView to its UIViewController? I know you can get from UIViewController to its UIView via [self view] but I was wondering if there is a reverse reference?

推荐答案

有关需求的一些意见:


  • 您的视图不应直接访问视图控制器。

  • 视图应该独立于视图控制器,并且能够在不同的上下文中工作。

  • 如果您需要视图以视图控制器的方式进行界面,推荐的方式,以及Apple在Cocoa中使用的方式是使用委托模式。

如何实现它的示例如下:

An example of how to implement it follows:

@protocol MyViewDelegate < NSObject >

- (void)viewActionHappened;

@end

@interface MyView : UIView

@property (nonatomic, assign) MyViewDelegate delegate;

@end

@interface MyViewController < MyViewDelegate >

@end

视图与其委托接口$ c> UITableView ),它不关心它是在视图控制器还是在你最终使用的任何其他类中实现。

The view interfaces with its delegate (as UITableView does, for instance) and it doesn't care if its implemented in the view controller or in any other class that you end up using.

我的原始答案如下:我不推荐这个,没有其他的回答,直接访问视图控制器

没有内置的方法可以做到。虽然你可以通过在 UIView 上添加 IBOutlet 并在Interface Builder中连接这些, 。视图不应该知道视图控制器。相反,你应该像@Phil M建议和创建一个协议作为委托使用。

There is no built-in way to do it. While you can get around it by adding a IBOutlet on the UIView and connecting these in Interface Builder, this is not recommended. The view should not know about the view controller. Instead, you should do as @Phil M suggests and create a protocol to be used as the delegate.

这篇关于从UIView到UIViewController?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆