【问题标题】:Pass variables between two controllers in iOS在 iOS 中的两个控制器之间传递变量
【发布时间】:2017-09-30 04:33:27
【问题描述】:

我想从我的第一个控制器传递一些变量:

float user_distance;
UIImage *user;
float user_battery;
NSString *user_name;

到第二个控制器。 两者之间的联系是通过函数实现的:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

以这种方式:

    UserViewController *secondViewController = [[UserViewController alloc] initWithNibName:@"UserViewController" bundle:nil];
[self.navigationController pushViewController:secondViewController animated:YES];

如何从这个函数中恢复值?

提前致谢!

【问题讨论】:

  • 您管理数据源,因此从indexPath,您可以检索(数组?)数据源的值。您现在可以将这些值设置为 secondViewController。
  • 如何从 indexpath 中检索第一个变量的值?
  • 这取决于你如何编码tableView:cellForRowAtIndexPath:
  • secondViewController.device = [self.arrayOfDevices objectAtIndex:indexPath.row] 然后呢? UserViewController 具有 device 类 SEC_Device 的属性。

标签: ios objective-c uitableview xib


【解决方案1】:

将您需要的属性添加到 .h 文件中的第二个控制器..

//SecondController.h    
@interface SecondController : UIViewController
@property (nonatomic) float *property1;
@property (nonatomic, strong) UIImage *property2;
@property (nonatomic) float *property3;
@property (nonatomic, strong) NSString *property4;
@end

然后在您的第一个控制器 .m 文件中导入您的第二个控制器 .h 文件。 并在推送第二个控制器之前设置属性。

//FirstController.m
#import "SecondController.h"
...
...
UserViewController *secondViewController = [[UserViewController alloc] initWithNibName:@"UserViewController" bundle:nil];

secondViewController.property1 = ;//your value here
secondViewController.property2 = ;//your value here
secondViewController.property3 = ;//your value here
secondViewController.property4 = ;//your value here

[self.navigationController pushViewController:secondViewController animated:YES];

【讨论】:

  • 好的,谢谢!只是有点小错误,其实float的声明是没有“*”的!
猜你喜欢
  • 2015-07-22
  • 2012-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多