繁体   English   中英

iOS:将操作栏按钮委托给其他类

[英]iOS: Delegate action bar button to other class

我有一个带有容器的UIViewController,并且在导航栏上有一个UIBarButton,并且我希望按钮的动作进入另一个类,即View1的类。

我没有显示“嵌入Segue”的课程,因为它不是必需的。

当我单击按钮时,什么都没有发生,甚至日志(NSLog)中的信息也没有。

谁来帮帮我?

我有这个:

//  ViewController.h
#import <UIKit/UIKit.h>

@protocol changeDelegate <NSObject>
-(void) changeLabel;
@end

@interface ViewController : UIViewController

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

@end


//  ViewController.m
#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (IBAction)changeButton:(UIBarButtonItem *)sender {

    [self.delegate changeLabel];

}

@end
//  Container.h

#import <UIKit/UIKit.h>

@interface Container : UIViewController

@end


//  Container.m

#import "Container.h"

@interface Container ()

@end

@implementation Container

- (void)viewDidLoad {
    [super viewDidLoad];

    [self performSegueWithIdentifier:@"segueView1" sender:nil];

}


- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    [self addChildViewController:segue.destinationViewController];
    [self.view addSubview:((UIViewController *)segue.destinationViewController).view];

}

@end
//  View1.h

#import <UIKit/UIKit.h>

@interface View1 : UIViewController <changeDelegate>

@end


//  View1.m

#import "View1.h"

@interface View1 ()

@property (weak, nonatomic) IBOutlet UILabel *labelView1;

@end

@implementation View1

- (void)viewDidLoad {
    [super viewDidLoad];

}

-(void) changeLabel {
    NSLog(@"Button Action !");
    self.labelView1.text = @"Button Action !";
}

@end

谢谢,JProveta

我想问题是您的委托方法没有触发。 尝试将其添加到view.m的viewdidload中

Viewcontroller *obj  = [[Viewcontroller alloc]init];
obj.delegate = self;

您会看到没有调用-(void) changeLabel ,同时ViewController不知道它是谁的委托。 您应该为ViewController分配委托,在View1.m ,您应该有类似以下内容:

ViewController *vC = [ViewController new];
vC.delegate = self; // changeDelegate

然后

[self.delegate changeLabel];

类似于: [view1 changeLabel]; 然后调用changeLabel。


对于您的项目:

“ ViewController.h” -(IBAction)changeButton:(UIBarButtonItem *)sender {

    [[NSNotificationCenter defaultCenter] postNotificationName:@"change_label_notfication" object:nil];

    //[self.delegate changeLabel];
    NSLog(@"button");

}

“View1.h”

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor redColor];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeLabel) name:@"change_label_notfication" object:nil];
}

一些建议:

  1. ViewController是视图的控制器,因此@interface View1 : UIViewController <changeDelegate> View1不是一个好名字。 2.不确定为什么要这样做吗? 但这对于您的代码来说确实不是一个很好的结构。 ViewController.h可以设置标签可以控制器属性,“ Container.h”在您的视线中不会出现任何场景。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM