2013-12-22 114 views
0

我已经创建了一个视图和一个变量并将其加载到视图控制器的loadView方法中。如何在调用loadView方法后将值传递给视图控制器中的视图变量?以编程方式从视图控制器设置iOS设置视图

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? 
    } 

回答

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"; 
} 
相关问题