UIBarButtonItem 取消不起作用

UIBarButtonItem Cancel does not work

我想取消带有 UIBarButtonItem 的第二个视图控制器,但我只是没有得到正确的代码。请帮忙。

Viewcontroller.h

#import <UIKit/UIKit.h>
#import "SecondViewController.h"

@interface ViewController : UIViewController <SecondViewControllerDelegate>
@end

Viewcontroller.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.destinationViewController isKindOfClass:[SecondViewController class]]) {
        SecondViewController *vc2 = segue.destinationViewController;
        vc2.delegate = self;
    }
}

-(void)dismissViewController
{
    NSLog(@"dismissed");
    [self dismissViewControllerAnimated:YES completion:nil];
}
@end

Secondviewcontroller.h

#import <UIKit/UIKit.h>

@protocol SecondViewControllerDelegate <NSObject>

- (void) dismissViewController;

@end

@interface SecondViewController : UIViewController

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

- (IBAction)backBarButtonItemPressed:(UIBarButtonItem *)sender;
@end

BackbarButton 表示取消按钮

Secondviewcontroller.m

#import "SecondViewController.h"

@interface SecondViewController ()

@end

@implementation SecondViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)backBarButtonItemPressed:(UIBarButtonItem *)sender {
    [self.delegate dismissViewController];
}
@end

你可以在secondViewController中解雇,我在你的代码中没有看到Delegate的意思

- (IBAction)backBarButtonItemPressed:(UIBarButtonItem *)sender {
    [self dismissViewControllerAnimated:true completion:nil];
}

如果您使用 show segue,并且您有一个带有这两个 ViewController 的导航控制器,请使用

- (IBAction)dismiss:(id)sender {
   [self.navigationController popViewControllerAnimated:true];
}