ios - 如何从 View 中显示 View Controller ?

标签 ios objective-c iphone uiview uiviewcontroller

我搜索了类似 Get to UIViewController from UIView? 的答案和其他几个答案,但没有成功。

我的问题是我在 UIView 中有一个按钮让我们说 class1 当我点击那个按钮时我想加载另一个 View class2 这是 UIViewController,因为我没有在 class1 中得到 navigationController,所以我无法加载 class2查看。

请帮我解决这个问题。

谢谢, 提前。

最佳答案

一般来说,UIViews 不应包含任何触发应用程序流程的逻辑。这是 UIViewControllers 的工作。它只是一种使代码设计更好、更有条理的方法。

我经常使用的一种方法是在我的自定义 UIView 中使用 delegate 模式。这是简单的设置:

在您的 MyCustomView .h 文件中:

@class MyCustomView;

@protocol MyCustomViewDelegate <NSObject>
@optional
- (void)myViewDidTapOnButton:(MyCustomView)myCustomView;
@end


@interface MyCustomView : UIView

@property (weak, nonatomic) id <MyCustomViewDelegate> delegate;

@end

在您的 MyCustomView .m 文件中:

- (IBAction)didTapMyButton:(id)sender {

    if ([self.delegate respondsToSelector:@selector(myViewDidTapOnButton:)]) {
        [self.delegate myViewDidTapOnButton:self];
    }
}

然后在呈现您的 View 的 View Controller 中:

界面:

@interface MyViewController ()<MyCustomViewDelegate>

@property (weak, nonatomic) IBOutlet UIView *myCustomView;

和实现:

- (void)viewDidLoad {
    [super viewDidLoad];

    self.myCustomView.delegate = self;
}

- (void)myViewDidTapOnButton:(MyCustomView)myCustomView {
    ... code for presenting viewcontroller ...
}

注意: 即使您不使用此方法中发送的参数 myCustomView,始终将委托(delegate)的 sender 作为第一个参数发送也是一个常见的模式和好习惯。

这也被 Apple 大量使用,例如在

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;

关于ios - 如何从 View 中显示 View Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31586371/

相关文章:

iphone - connectionWithRequest 是同步的吗?

iphone - 具有 playerduel 功能的应用程序不会收到推送通知

java - 从 Java 6 升级到 Java 7/8 后,Apple 无法推送

ios - UIVisualEffectView 模糊约束动画错误

iphone - 如何更改 Root View Controller

JavaScriptCore -- 将函数作为参数传递给 ObjC

iphone - 图片加载到 UIWebView 时无法放大缩小

ios - 实时从服务器获取消息

android - 如何使用phonegap扫描条码

ios - 将 .caf 文件转换为规范化 float 组 Objective-C/C