将信息从视图控制器发送到另一个
Posted
技术标签:
【中文标题】将信息从视图控制器发送到另一个【英文标题】:Sending information from a view controller to another 【发布时间】:2013-03-08 16:23:16 【问题描述】:问题是,我在视图控制器 (ViewController) 上有 9 个按钮,并且我有一个插座集合用于存储所有这些按钮插座。
然后我有一个动作方法来处理这些按钮的点击事件。
我想要的是发送 CLICKED 按钮的按钮图像背景(作为 UIImage * img),segue 到另一个视图控制器(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”... 有什么建议么?谢谢
【问题讨论】:
为什么for
循环会覆盖self.image
?
【参考方案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 *),然后消除循环。
【讨论】:
以上是关于将信息从视图控制器发送到另一个的主要内容,如果未能解决你的问题,请参考以下文章