我已经遵循了几个关于在视图控制器之间传递数据的指南,但它们似乎涉及在任何等效的 -(void)goToNextView 方法中设置 secondViewController 的属性。我试图弄清楚如何在使用应用程序委托中创建的标签栏控制器时从第一个视图控制器中为第二个视图控制器中的属性分配值。
当前设置:
AppDelegate.m
@synthesize window;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
...
UITabBarController *tbc = [[UITabBarController alloc] init];
FirstViewController *vc1 = [[FirstViewController alloc] init];
SecondViewController *vc2 = [[SecondViewController alloc] init];
[tbc setViewControllers: [NSArray arrayWithObjects: vc1, vc2, nil]];
[[self window] setRootViewController:tbc];
[self.window makeKeyAndVisible];
return YES;
}
...
@end
第一视图控制器.h
#import "SecondViewController.h"
@interface FirstViewController : UIViewController
{
SecondViewController *vc2;
IBOutlet UISlider *sizeSlider;
}
@property (nonatomic, retain) SecondViewController *vc2;
@property (strong, nonatomic) UISlider *mySlider;
-(IBAction) mySliderAction:(id)sender;
@end
第一视图控制器.m
#import "FirstViewController.h"
#import "SecondViewController.h"
@implementation FirstViewController
@synthesize vc2, mySlider;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
UITabBarItem *tbi = [self tabBarItem];
[tbi setTitle:@"xib"];
}
return self;
}
...
- (IBAction) mySliderAction:(id)sender
{
NSString *str = [[NSString alloc] initWithFormat:@"%3.2f", mySlider.value];
if(self.vc2 == nil)
{
SecondViewController *viewTwo = [[SecondViewController alloc] initWithNibName:nil bundle:nil];
self.vc2 = viewTwo;
}
vc2.sliderValueString = str;
}
...
@end
SecondViewController.h
#import <UIKit/UIKit.h>
#import "myView.h"
@interface SecondViewController : UIViewController
{
NSString *sliderValueString;
}
@property (copy) NSString *sliderValueString;
@end
第二视图控制器.m
#import "SecondViewController.h"
@implementation SecondViewController
@synthesize sliderValueString;
- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)bundle
{
self = [super initWithNibName:nil bundle:nil];
if (self) {
UITabBarItem *tbi = [self tabBarItem];
[tbi setTitle:@"View 2"];
}
return self;
}
-(void) loadView
{
CGRect frame = [[UIScreen mainScreen] bounds];
myView *view = [[myView alloc] initWithFrame:frame];
printf("Slider Value: %s", [sliderValueString UTF8String]);
[self setView: view];
}
...
@end
myView.h 和 .m 可能与问题无关,但我有 .h 子类化 UIView,并且 .m 使用 -(id)initWithFrame:(CGRect)frame 创建视图
我猜我将第二个 VC 的属性分配在错误的位置(mySliderAction),因为第二个 VC 中的 printf() 是空白的,所以我的问题是:应该在哪里分配属性,或者我是什么做错了阻止第二个 VC 允许它的 sliderValueString 不被(或保持)分配?
谢谢!