如何从视图中显示 viewcontroller?

How to show viewcontroller from the view?

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

我的问题是我在 UIView 中有一个按钮让我们说 class1 并且当我单击该按钮时我想加载另一个视图 class2UIViewController,因为我在 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];
    }
}

然后在你的 viewcontroller 中呈现你的观点:

接口:

@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,始终将委托的 sender 作为第一个参数发送也是一个常见的模式和好习惯。

Apple也经常使用这个,例如在

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

两种情况:

  • 如果你正在使用故事板,那么给你的 NavigationController 一个 故事板 ID。并在你的中创建一个 navigationController 的对象 自定义 UIView class。

  • 如果您自定义了从 AppDelegate 启动的应用,请创建一个 public propertynavigationController。从你的 UIView class 创建一个带有 [UIApplication sharedApplication].delegate 的 appDelegate 对象。从此对象访问 navigationController property

当您拥有 navigationController 对象时,您可以使用以下方式推送 viewcontroller:

[navigationController pushViewController:ViewController animated:YES];

当你点击你的按钮时,你可以这样做:

YouViewController *yourViewController = [YouViewController new];
[self.view addSubView:yourViewController.view];

希望能帮到你。

首先用 "MyViewController" 填充情节提要 ID,这是一个字符串字段,您可以使用它根据情节提要 ViewController 创建新的 ViewController。然后像这样访问该视图控制器:

- (IBAction)buttonPressed:(id)sender{
    MyCustomViewController *newvc = [self.storyboard instantiateViewControllerWithIdentifier:@"MyViewController"];
   [self presentViewController:newvc animated:YES completion:nil];
}