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

最佳答案

您已经为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";
}

10-07 20:29