-2

可以通过单击其他视图控制器内的按钮来更改图像吗?我使用此代码将数据从 ViewController 传递到 SecondViewController。我想将突击队添加到同一个按钮以将图像添加到 SecondViewController ......请原谅我的糟糕问题......

视图控制器.h

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

@interface ViewController : UIViewController <SecondViewControllerDelegate> {

IBOutlet UITextField *userNameTextField;
}

@property (nonatomic, strong) UITextField *userNameTextField;

@end

视图控制器.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

第二视图控制器.m

#import "SecondViewController.h"

@interface SecondViewController ()

@end

@implementation SecondViewController

@synthesize someText;
@synthesize delegate = _delegate;

- (IBAction)returnButtonPressed:(id)sender {

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

@end
4

2 回答 2

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];
于 2013-10-12T04:43:16.040 回答
-1

换另一个是什么意思UIViewController。因为当您单击当前时UIViewController,这意味着当前位于顶部且可见。你所谓的另一个只能是重叠不活动的,或者它现在不存在。

因此,如果您想以某种方式UIImage从另一个 UI 更改,最简单的方法是将UIImage或图像文件名保存在全局存储区域中,例如您的AppDelegate类、文件。单击更改全局区域内容时。在图像显示的 ui 中,您可以添加一些代码

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

是你想要的吗?

于 2013-10-12T03:51:34.223 回答