在iOS中从一个viewController返回到另一个时,对象返回null

时间:2014-01-10 13:02:33

标签: ios objective-c

我使用的是两个视图控制器:RegisterViewControllerExp

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];
}

4 个答案:

答案 0 :(得分:1)

您可以做的简单事情就是使用NSNotificationCenter。所以只需在firstOneViewController中添加观察者并将其发布到另一个ViewController中。在通知方法的FirstViewController中,只需设置UIButton

的图像

答案 1 :(得分:0)

您需要在这两个控制器之间使用委托

您的RegisterViewController将定义协议和委托对象,如

@protocol RegisterViewControllerDelegate

-(void)chageImage:(id)sender;

@end

然后定义委托属性,然后您的ExpViewController将实现您的委托,此方法将更改您的图片

答案 2 :(得分:0)

在加载视图控制器之前,无法设置其他视图的控制器出口属性。相反,你应该在RegisterViewController中声明NSString的属性,然后在Exp中设置它,然后在RegisterViewController的viewDidLoad上,获取NSString属性的值并从中创建UIImage并将其设置为RegisterViewController的profileBut按钮上的背景图像。

答案 3 :(得分: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"]];
      }
}
Exp viewController中的

@implemenration Exp : UIViewController

-(void)dissmissView
{

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

    [self dismissViewControllerAnimated:YES completion:nil];
}