我有两个 ViewController:A 和 B,
我正在A中计算B的变量,然后通过创建ViewController B的对象来推送B及其变量值。B的变量在其自身中声明。现在我正在更改 ViewController B 中变量的值并返回到 A。我想使用 A 中变量的更改值。我已经尝试过此协议(protocol),但在 A 中我得到该变量的 0 值。 这是我的代码:
ViewController啊
#import <UIKit/UIKit.h>
#import "B.h"
@class B;
@interface ViewController : UIViewController<nxtDelegate>
{
int vcheck;
}
@property(nonatomic,assign) int vcheck;
实现A:
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize lbl,txt,vcheck;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
-(void)viewWillAppear:(BOOL)animated{
NSLog(@"vcheckis:%d",vcheck);
}
-(void)chngvalue:(int)i{
vcheck=i;
}
ViewController B.h
#import <UIKit/UIKit.h>
@protocol nxtDelegate <NSObject>
-(void)chngvalue:(int )i;
@end
@interface nextviewController : UIViewController<UITableViewDelegate,UIPickerViewDelegate,UIPickerViewDataSource>
{
int chcek;
}
@property(weak,nonatomic)id<nxtDelegate> delegate;
- (IBAction)btnclick:(id)sender;
@property(nonatomic,assign) int chcek;
ViewController B.m
- (IBAction)chngAction:(id)sender {
[_delegate chngvalue:chcek];
NSLog(@"%@",_delegate);}
最佳答案
我不知道为什么它不起作用,但我只是执行以下操作,它对我来说效果很好
@property(nonatomic, assign)id<nxtDelegate> Delegate;
合成属性名Delegate
@synthesize Delegate;
在推送期间我设置了委托(delegate)
ViewControllerB *ViewControllerBObj=[[ViewControllerB alloc] init];
[ViewControllerBObj setDelegate:self];
[[self navigationController] pushViewController:ViewControllerBObj animated:YES];
在 IBAction 中
- (IBAction)chngAction:(id)sender
{
if([[self Delegate] respondsToSelector:@selector(chngvalue:)])
[[self Delegate] chngvalue:chcek];
}
关于ios - 如何使用协议(protocol)在两个 View Controller 之间传递值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20422395/