【问题标题】:UIBarButtonItem Cancel does not workUIBarButtonItem 取消不起作用
【发布时间】:2015-07-20 14:07:34
【问题描述】:

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

【问题讨论】:

  • 当你的dismissViewController 在你的SecondViewController.h 中声明时,为什么你的dismissViewController 在你的第一个ViewController 中实现?
  • 从第一个 VC 中解散并调用第二个 VC
  • 但是如果你不使用它,你为什么要在你的第二个视图控制器中声明它。无论如何,如果此按钮不会保存任何数据而您只想退出,请尝试 ctrl + 从按钮拖动到情节提要上的 Exit 插座

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


【解决方案1】:

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

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

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

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

【讨论】:

  • Ty 用于回答,这确实有效,但仍然没有被解雇。我试图代表从第一个 VC 中解散。
  • 你用的是什么类型的segue?
  • 我使用了从第一个 VC 中的 UIBarButtonItem 到第二个 VC 的显示 segue 全部在情节提要中完成
  • 如果你有一个navigationController,请使用popViewControllerAnimated,看看我更新了什么
猜你喜欢
  • 1970-01-01
  • 2020-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-16
相关资源
最近更新 更多