2013-10-12 165 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

相關問題