ios – 从UIView使用presentViewController

我正在为我的iOS应用程序创建一个标题栏,我正在使用UIView。我唯一遇到的问题是“主页按钮”。当按住主页按钮时,需要转到主页,即ViewController。

但是,它看起来不像[self presentViewController:vc animated:NO completion:NULL];为UIView工作。

如何解决这个问题?

- (void) createTitlebar {

    CGRect titleBarFrame = CGRectMake(0,320,55);

    //Create the home button on the top right of the page. When clicked,it will navigate to the home page of the application
    homeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    homeButton.frame = CGRectMake(275,10,40,40);
    [homeButton setTag:1];
    [homeButton setImage:[UIImage imageNamed:@"homeIcon.png"] forState:UIControlStateNormal];
    [homeButton addTarget:self action:@selector(homeButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:homeButton];
}

- (IBAction)homeButtonPressed:(id)sender{

    //Transition to the submit button page
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
    ViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"ViewController"];
    [vc setModalPresentationStyle:UIModalPresentationFullScreen];
    [self presentViewController:vc animated:NO completion:NULL];
}

解决方法

只有UIViewController可以呈现另一个视图控制器,所以如果你需要从视图中显示一个viewcontroller,有几种方式,其中之一就是这样:

做一个视图控制器,您的父视图位于该视图的代表处

ParentView *view = [ParentView new];
...
view.delegate = self;

那么,在ParentView的内部调用方法的那个委托

- (IBAction)homeButtonPressed:(id)sender {
    [self.delegate buttonPressed];
}

然后在你的VC实现中

-(void)buttonPressed {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
    ViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"ViewController"];
    [vc setModalPresentationStyle:UIModalPresentationFullScreen];
    [self presentViewController:vc animated:NO completion:NULL];
}

如果你需要保持这个代码在UIView中,并避免授权,你可以做一个这样的技巧(个人我不喜欢它,但它应该工作)

-(void)buttonPressed{
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
    ViewController *vc = [storyboard      instantiateViewControllerWithIdentifier:@"ViewController"];
    [vc setModalPresentationStyle:UIModalPresentationFullScreen];
    [(UIViewController*)self.nextResonder presentViewController:vc animated:NO completion:NULL];
}

相关文章

在有效期内的苹果开发者账号(类型为个人或者公司账号)。还...
Appuploader官网--IOS ipa上传发布工具,证书制作工具跨平台...
苹果在9月13号凌晨(北京时间)发布 iOS 16,该系统的设备可...
计算机图形学--OpenGL递归实现光线追踪
Xcode 14打出来的包在低版本系统运行时会崩溃,报错信息是Li...