以编程方式从视图控制器设置iOS视图变量

时间:2013-12-22 10:47:02

标签: ios variables model-view-controller view viewcontroller

我用变量创建了一个视图,并将其加载到视图控制器的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?
    }

1 个答案:

答案 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";
}