2014-01-10 125 views
0

我正在使用兩個視圖控制器:RegisterViewControllerExp對象在iOS中從一個viewController返回到另一個時返回null

RegisterViewController包含一個IBOutlet按鈕,並且該按鈕的值在第一次加載視圖時設置。但我需要從另一個視圖控制器(Exp)更改按鈕圖像。

我該怎麼做?

#import <UIKit/UIKit.h> 

@interface RegisterViewController : UIViewController 
@property (nonatomic,strong)IBOutlet UIButton *but; 
-(void)Image:(UIImage*)img; 
@end 

@implementation RegisterViewController 
@synthesize but; 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    NSLog(@"but :%@",self.but);//<UIButton: 0xa581ed0; frame = (119 270; 62 62); opaque = NO; autoresize = RM+BM; layer = <CALayer: 0xa581b50>> 
} 


-(void)Image:(UIImage*)img 
{ 
    NSLog(@"but:%@",self.but);// returns null Value 
    [self.profileBut setBackgroundImage:img forState:UIControlStateNormal];//I can’t change image by this line.What is the problem? 
} 

@end 

#import <UIKit/UIKit.h> 
#import "RegisterViewController.h" 

@interface Exp : UIViewController 
@property (nonatomic,strong)RegisterViewController *regCont; 
@end 

@implementation Exp 
@synthesize regCont; 

-(void)dissmissView 
{ 
    self.regCont = [[RegisterViewController alloc]init]; 
    [regCont Image:[UIImage imageNamed:@"cute_cat_1.jpg"]]; 
    [self dismissViewControllerAnimated:YES completion:nil]; 
} 
+0

你並不需要爲''RegisterViewController新的對象,但是,使用的是之前創建的同一個實例。或者你需要實現代表。 –

+0

是很明顯,因爲如果你的視圖不在屏幕上,IBOutlets不會引用任何UIComponents。您可以在ViewDidLoad或ViewWillAppear中設置圖像 – Suryakant

+0

@prashant如何從Exp訪問我的RegisterViewController方法? – IKKA

回答

0

您需要使用這兩個控制器之間的代表團

RegisterViewController將定義一個協議和委託對象就像

@protocol RegisterViewControllerDelegate 

-(void)chageImage:(id)sender; 

@end 

然後定義委託財產然後你的ExpViewController將實現你的委託,這種方法將c更改圖像

0

在加載視圖控制器之前,您無法設置其他視圖的控制器插座屬性。相反,你應該在RegisterViewController中聲明一個NSString屬性,並將其設置爲Exp,然後將其設置爲RegisterViewController的viewDidLoad,獲取該NSString屬性的值並創建UIImage並將其設置爲RegisterViewController的profileBut按鈕上的背景圖像。

1

那麼你可以做的簡單的事情是使用NSNotificationCenter。因此,只需在firstOneViewController中添加觀察者並將其發佈到另一個ViewController中即可。並且在通知方法的FirstViewController中,只需設置UIButton的圖像即可。

0

試試這個....

#import <UIKit/UIKit.h> 

@implementation RegisterViewController 
- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    NSLog(@"but :%@",self.but);//<UIButton: 0xa581ed0; frame = (119 270; 62 62); opaque = NO; autoresize = RM+BM; layer = <CALayer: 0xa581b50>> 

    [[NSNotificationCenter defaultCenter] addObserver:self 
     selector:@selector(receiveTestNotification:) 
     name:@"TestNotification" 
     object:nil]; 
} 

implement selector method 

- (void) receiveTestNotification:(NSNotification *) notification 
{ 
     if ([[notification name] isEqualToString:@"TestNotification"]) 
     { 
      [self Image:[UIImage imageNamed:@"cute_cat_1.jpg"]]; 
     } 
} 

在進出口的viewController

@implemenration Exp : UIViewController 

-(void)dissmissView 
{ 

    [[NSNotificationCenter defaultCenter] 
     postNotificationName:@"TestNotification" 
     object:self]; 

    [self dismissViewControllerAnimated:YES completion:nil]; 
}