从视图控制器向另一个控制器发送信息

时间:2013-03-08 16:23:16

标签: ios uibutton uiimage segue viewcontroller

问题是,我在viewcontroller(ViewController)上有9个按钮,我有一个插座集合用于存储所有这些按钮插座。

然后我有一个处理这些按钮的点击事件的动作方法。

我想要的是发送CLICKED按钮的按钮图像背景(作为UIImage * img),segue到另一个viewcontroller(vc2),

这是我的代码:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *cardBtns;


- (IBAction)cardAction:(id)sender;

@end




#import "ViewController.h"
#import "ResultViewController.h"

@interface ViewController ()
@property(strong,nonatomic)UIImage *image;
@end

@implementation ViewController

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

- (IBAction)cardAction:(id)sender {
for(UIButton *cardButton in self.cardBtns){
    self.image = [cardButton currentBackgroundImage];
}
[self performSegueWithIdentifier:@"cardSegue" sender:self.image];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
//UIImage * img = [UIImage imageNamed:@"f1"];
UIImage * img = (UIImage *)sender;

ResultViewController *viewcontroller = [segue destinationViewController];
viewcontroller.img = img;
}

@end

在vc2中,我在这里有另一个按钮,我希望用刚刚从vc1 segue发送的img绘制这个按钮背景img。

@interface ResultViewController : UIViewController
@property (weak, nonatomic) IBOutlet UIButton *cardBtn;
@property(strong,nonatomic)UIImage *img;

- (IBAction)cardDismiss:(id)sender;

@end



#import "ResultViewController.h"

@interface ResultViewController ()

@end

@implementation ResultViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
    // Custom initialization
}
return self;
}

- (void)viewDidLoad
{
[super viewDidLoad];
[self.cardBtn setImage:self.img forState:UIControlStateNormal];
}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}


- (IBAction)cardDismiss:(id)sender {
[self dismissViewControllerAnimated:NO completion:nil];
}
@end

假设我的按钮是1,2,3,4,5,6,7,8,9

现在,无论我在vc1中点击什么按钮,它总是在vc2中显示为'6'... 有什么建议?感谢

1 个答案:

答案 0 :(得分:1)

问题在于:

- (IBAction)cardAction:(id)sender {
for(UIButton *cardButton in self.cardBtns){
    self.image = [cardButton currentBackgroundImage];
}
[self performSegueWithIdentifier:@"cardSegue" sender:self.image];
}

这会将self.image设置为self.cardBtns中的最后一项。您希望将self.image设置为sender.currentBackgroundImage(并将参数类型中的id更改为UIButton *),然后消除循环。