0

I've created a view with a variable and loaded it in the loadView method of a view controller. How do I pass a value to the view variable from the view controller after the loadView method has been called?

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 Answer 1

1

You've already set up the locationTitle property for LocationView objects, so you can just access that. The only thing you need to do beforehand is keep a reference to the LocationView object around in an instance variable so you can access it from any instance method.

@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

Alternatively, since you are assigning the custom view to the view controllers main view, you could cast that:

- (void)viewDidLoad
{
    [super viewDidLoad];
    ((LocationView *)self.view).locationTitle = @"Test";
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.