當我嘗試從子視圖訪問我的主ViewController中的方法時,我的應用程序崩潰。Xcode:如何從子類訪問方法?
請幫忙。
我在我的主ViewController中有一個UIButton,它改變了UILabel中的文本,這也在我的主視圖中。在SubView中有一個UIButton,它應該通過訪問主ViewController中的相同方法來再次更改字符串。但該應用程序崩潰。
這裏是我的代碼:
主視圖控制器
ViewController.h
#import <UIKit/UIKit.h>
#import "SubViewController.h"
@interface ViewController : UIViewController
@property (nonatomic, strong) UILabel *label;
@property (nonatomic, retain) UIButton *mainClassButton;
- (void) setLabelTo:(NSString *)copy;
@end
ViewController.m
#import "ViewController.h"
@interface ViewController()
@end
@implementation ViewController
@synthesize label;
@synthesize mainClassButton;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.label = [[UILabel alloc] initWithFrame:CGRectMake(30.0, 30.0, 200.0, 30.0)];
self.label.text = @"Let's Go Mets!";
[self.view addSubview:label];
mainClassButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
mainClassButton.frame = CGRectMake(30.0, 70.0, 200.0, 30.0);
[mainClassButton setTitle:@"Main Class Button" forState:UIControlStateNormal];
[mainClassButton addTarget:self action:@selector(touchAction:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:mainClassButton];
SubViewController *subViewController = [[SubViewController alloc] init];
subViewController.view.backgroundColor = [UIColor clearColor];
[self.view addSubview:subViewController.view];
[self.view bringSubviewToFront:self.mainClassButton];
}
- (IBAction)touchAction:(UIButton *) sender
{
[self setLabelTo:@"Here we go Yankess!"];
}
- (void) setLabelTo:(NSString *)copy
{
self.label.text = copy;
}
子視圖控制器
個SubViewController.h
#import <UIKit/UIKit.h>
#import "ViewController.h"
@interface SubViewController : UIViewController
@property (nonatomic, retain) UIButton *subClassButton;
@end
SubViewController.m
@implementation SubViewController
@synthesize subClassButton;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
subClassButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
subClassButton.frame = CGRectMake(30.0, 115.0, 200.0, 30.0);
[subClassButton setTitle:@"Sub Class Button" forState:UIControlStateNormal];
[subClassButton addTarget:self action:@selector(touchAction:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:subClassButton];
}
- (IBAction)touchAction:(UIButton *) sender
{
ViewController *vc = [[ViewController alloc] init];
[vc setLabelTo:@"If you ask me, I prefer the White Sox."];
}
我仍然是一種新的Xcode和Objective-C,我會感激你可以提供任何幫助。
感謝
您可以包括控制檯輸出,所以我們可以看到你的錯誤? –