可以通过单击其他视图控制器内的按钮来更改图像吗? 我使用此代码将数据从ViewController传递给SecondViewController。我想在同一个按钮上添加一个用于向SecondViewController添加图像的命令...请原谅我可怜的问题......
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
答案 0 :(得分:1)
以下是一种适合您的方式:
只需在ViewController中使用图像设置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 :(得分:-1)
更改另一个UIViewController
的意思是什么。因为当您点击当前UIViewController
时,这意味着当前位于顶部且可见。你所谓的另一个只能重叠不活动,或者它现在不存在。
因此,如果您想以某种方式从另一个UI更改UIImage
,最简单的方法是将UIImage
或图像文件名保存在全局存储区域,例如AppDelegate
类,文件。单击时更改全局区域内容。在ui for image show中你可以添加一些代码
- (void)viewWillAppear:(BOOL)animated {
//read and change UIImage content from global store
}
是你想要的吗?