我用变量创建了一个视图,并将其加载到视图控制器的loadView方法中。在调用loadView方法后,如何将值传递给视图控制器?
LocationView.m
#import "LocationView.h"
@implementation LocationView
@synthesize locationTitle;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
locationTitle = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, 300, 20)];
[self addSubview:locationTitle];
}
return self;
}
LocationViewController.m
#import "LocationViewController.h"
#import "LocationView.h"
@interface LocationViewController ()
@end
@implementation LocationViewController
- (void)loadView
{
CGRect frame = [[UIScreen mainScreen] bounds];
LocationView *locationView = [[LocationView alloc] initWithFrame:frame];
[self setView:locationView];
}
- (void)viewDidLoad
{
[super viewDidLoad];
How do I pass a value to locationTitle here?
}
答案 0 :(得分:1)
您已经为locationTitle
个对象设置了LocationView
属性,因此您只需访问该属性即可。您需要事先做的唯一事情是在实例变量中保留对LocationView
对象的引用,以便您可以从任何实例方法访问它。
@implementation LocationViewController {
LocationView *_locationView;
}
- (void)loadView
{
CGRect frame = [[UIScreen mainScreen] bounds];
_locationView = [[LocationView alloc] initWithFrame:frame];
[self setView:_locationView];
}
- (void)viewDidLoad
{
[super viewDidLoad];
_locationView.locationTitle = @"Test";
}
@end
或者,由于您要将自定义视图分配给视图控制器主视图,因此可以强制转换:
- (void)viewDidLoad
{
[super viewDidLoad];
((LocationView *)self.view).locationTitle = @"Test";
}