2013-10-12 37 views
-2

可以通过单击其他视图控制器内的按钮来更改图像? 我使用此代码为了将数据从ViewController传递到SecondViewController。我希望添加到同一个按钮突击队将图像添加到SecondViewController ......原谅我那可怜的问题...在两个视图控制器之间更改UIImage视图

ViewController.h

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

@interface ViewController : UIViewController <SecondViewControllerDelegate> { 

IBOutlet UITextField *userNameTextField; 
} 

@property (nonatomic, strong) UITextField *userNameTextField; 

@end 

ViewController.m

#import "ViewController.h" 
#import "SecondViewController.h" 

@interface ViewController() 

@end 

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{ 
if([segue.identifier isEqualToString:@"to2"]){ 
    SecondViewController *viewController = segue.destinationViewController; 
    viewController.delegate = self; 
} 
} 

- (void)done:(NSString *)name{ 
[self dismissViewControllerAnimated:YES completion:nil]; 
NSLog(@"Back in first ViewController, metod Done, with name=%@",name); 
userNameTextField.text=name; 
} 

@end 

SecondViewController.h

#import <UIKit/UIKit.h> 

@protocol SecondViewControllerDelegate <NSObject> 

-(void) done:(NSString*)someText; 

@end 

@interface SecondViewController : UIViewController { 

IBOutlet UITextField *someText; 
IBOutlet UIButton *returnButton; 
id delegate; 
} 

@property (nonatomic, assign) id <SecondViewControllerDelegate> delegate; 

@property (nonatomic, strong) UITextField *someText; 

- (IBAction)returnButtonPressed:(id)sender; 

@end 

SecondViewController.m

#import "SecondViewController.h" 

@interface SecondViewController() 

@end 

@implementation SecondViewController 

@synthesize someText; 
@synthesize delegate = _delegate; 

- (IBAction)returnButtonPressed:(id)sender { 

[self.delegate done:someText.text]; 
} 

@end 

回答

1

下面是应为你工作的一种方式:

刚刚成立了一个NSNotification与图像的视图控制器。当按下按钮时触发另一个viewController中的通知。

在图像的视图控制器

在按钮视图控制器
//in ViewDidLoad: 
     [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeTheImage) name:@"CHANGE_THE_IMAGE" object:nil]; 


    //then elsewhere in the class: 
    - (void)changeTheImage { 
     //change your image here 
    } 


    //and in your dealloc, make sure you add this, or it will keep "observing" 
    [[NSNotificationCenter defaultCenter] removeObserver:self]; 

然后:

//have this as your button action (or add the line to your button action) 
- (IBAction)yourButtonWasPressed:(id)sender { 
    [[NSNotificationCenter defaultCenter]postNotificationName:@"CHANGE_THE_IMAGE" object:self]; 
-1

什么意思改变另一个UIViewController。因为当你点击当前的UIViewController这意味着当前是在顶部和可见。你所谓的另一个只能重叠不活动或它现在不存在。

所以,如果你想以某种方式向UIImage从另一个UI改变,最简单的方法就是保持在全局存储区域UIImage或图像文件名,如您AppDelegate类文件。点击更改全球区域内容时。并在图像显示你可以添加一些代码

- (void)viewWillAppear:(BOOL)animated { 
    //read and change UIImage content from global store 
} 

是你想要的吗?

+0

我希望添加到同一个按钮命令将图像添加到SecondViewController ...原谅我可怜的问题... – Swr79