我想使用委托将数据从第二个选项卡传递到第一个选项卡。但委托方法未触发。这是代码(我正在使用情节提要)
在 SecondViewController.h
#import <UIKit/UIKit.h>
@class SecondViewController;
@protocol SecondViewControllerDelegate <NSObject>
-(void) sliderValueDidChanged: (SecondViewController *)controller data:(float) sliderValue;
@end
@interface SecondViewController : UIViewController{
__weak id<SecondViewControllerDelegate> delegate;
}
- (IBAction)sliderPressed:(id)sender;
@property (weak, nonatomic) IBOutlet UISlider *mySlider;
@property(weak,nonatomic) id<SecondViewControllerDelegate> delegate;
@end
在 SecondViewController.m
#import "SecondViewController.h"
@interface SecondViewController ()
@end
@implementation SecondViewController
@synthesize mySlider;
@synthesize delegate;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)viewDidUnload
{
[self setMySlider:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (IBAction)sliderPressed:(id)sender {
float value = mySlider.value;
[self.delegate sliderValueDidChanged:self data:value];
NSLog(@"%@",self.delegate);
}
@end
第一视图控制器.h
#import <UIKit/UIKit.h>
#import "SecondViewController.h"
@interface FirstViewController : UIViewController<SecondViewControllerDelegate>
@property (weak, nonatomic) IBOutlet UILabel *myLabel;
@end
在 FirstViewController.h
#import "FirstViewController.h"
@interface FirstViewController ()
@end
@implementation FirstViewController
@synthesize myLabel;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
SecondViewController *svc = [[SecondViewController alloc]init];
svc.delegate = self;
}
- (void)viewDidUnload
{
[self setMyLabel:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
-(void) sliderValueDidChanged: (SecondViewController *)controller data:(float) sliderValue{
myLabel.text = [[NSString alloc]initWithFormat:@"%f",sliderValue];
NSLog(@"delegate called");
}
@end
我正在尝试在第二个选项卡中设置一个滑块并将边值发送到具有标签的第一个选项卡。self.delegate 打印 null 并且从未调用过委托方法。