UIBarButtonItem取消不起作用

时间:2015-07-20 14:07:34

标签: ios objective-c delegates uibarbuttonitem cancel-button

我想用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

1 个答案:

答案 0 :(得分:2)

你可以在secondViewController中解雇,我在你的代码中没有看到代表的含义

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

如果你使用show segue,并且你有一个带有这两个ViewControllers的navigationController,请使用

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