如何访问在另一个类中创建的IBOutlet?
这是我的代码...... 第一类
·H
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property (retain, readwrite) IBOutlet UIView *myView;
@end
的.m
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize myView;
- (void)viewDidLoad {
[super viewDidLoad];
}
@end
二级
·H
#import <UIKit/UIKit.h>
@interface ViewController2 : UIViewController
- (IBAction)accion:(id)sender;
- (IBAction)btnBack:(id)sender;
@end
的.m
#import "ViewController.h"
#import "ViewController2.h"
@interface ViewController2 ()
@end
@implementation ViewController2
- (void)viewDidLoad {
[super viewDidLoad];
}
- (IBAction)accion:(id)sender {
ViewController *a = [ViewController new];
UIView *someView = [a myView];
[someView setBackgroundColor:[UIColor redColor]];
}
- (IBAction)btnBack:(id)sender {
[self dismissViewControllerAnimated:YES completion:nil];
}
@end
为什么不行?在我的观点返回时没有更改backgroundColor
答案 0 :(得分:1)
我认为您尝试委托模式来设置值Viewcontroller2.h
文件
像这样添加协议......
#import <UIKit/UIKit.h>
@protocol tutorialDelegate <NSObject> //set protocol
-(void)delegatesDescribedWithDescription;
@end
@interface ViewController2 : UIViewController
@property (weak, nonatomic) id<tutorialDelegate> tutorialDelegate1;
- (IBAction)accion:(id)sender;
- (IBAction)btnBack:(id)sender;
@end
在viewcontroller2.m
文件中声明协议后首先合成并调用这样的方法..
#import "ViewController.h"
@interface ViewController2 ()
@end
@implementation ViewController2
@synthesize tutorialDelegate1; // synthesize here
- (void)viewDidLoad {
[super viewDidLoad];
}
- (IBAction)accion:(id)sender {
ViewController *a = [ViewController new];
UIView *someView = [a myView];
[someView setBackgroundColor:[UIColor redColor]];
}
- (IBAction)btnBack:(id)sender {
// Here we tell delegate to invoke method in parent view.
[self.tutorialDelegate1 delegatesDescribedWithDescription
];
[self dismissViewControllerAnimated:YES completion:nil];
}
@end
最后我们在视图controller.m
文件中实现此方法,但首先在viewcotroller.h
文件中设置委托,如下所示...
#import <UIKit/UIKit.h>
#import "ViewController2.h" //import here
@interface ViewController : UIViewController <tutorialDelegate> //set delegate
@property (retain, readwrite) IBOutlet UIView *myView;
@end
和viewcontroller.m
文件
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize myView;
- (void)viewDidLoad {
[super viewDidLoad];
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:@"yourIdentifier"]) {
ViewController2 *detailViewController =
segue.destinationViewController;
// here we set the ViewController to be delegate in
// detailViewController
detailViewController.tutorialDelegate1 = self;
}
}
// ViewController must implement tutorialDelegate's methods
// because we specified that ViewController will conform to
// tutorialDelegate protocol
-(void)delegatesDescribedWithDescription
{ // here your code please
viewTemp.backgroundColor =[UIColor redColor];
}
@end