Flappy
Flappy

Reputation: 867

Objective-c iPhone read and change UILabel position from another class

I try to change the read and change the position from a UILabel. This UILabel has been created in Interface Builder and now i want to read and change the position inside another class, when i call a method in the MainVieController class.

But how can i do that, i've read several forums but i can't get it work. Here's also some sample code. I hope someone can help me with this.

MainViewController.h

#import <UIKit/UIKit.h>
@class NewClass;

@interface MainViewController : UIViewController {

    UILabel *daLabel;

}

@property (nonatomic, retain) IBOutlet UILabel *daLabel;

@end

MainViewController.m

#import "MainViewController.h"
#import "NewClass.h"

@implementation MainViewController
@synthesize daLabel;

- (void)viewDidLoad {

    [super viewDidLoad];

    NewClass *anotherClass = [[NewClass alloc] init];
    [anotherClass test];

}

@end

NewClass.h

#import <Foundation/Foundation.h>
@class MainViewController;

@interface NewClass : NSObject {

}

@end

NewClass.m

#import "NewClass.h"
#import "MainViewController.h"

@implementation NewClass

- (void)test {

    MainViewController *MainController = [[MainViewController alloc] init];

    CGRect labelPosition = MainController.daLabel.frame;
    NSLog(@"POSITION: %f", labelPosition.origin.x); // Returns 0.000000

}

@end

Upvotes: 0

Views: 6780

Answers (1)

spstanley
spstanley

Reputation: 950

I'm not sure why you're creating another instance of your view controller in NewClass, which is loaded by your view controller. Maybe just pass "self" in the call to the test method? But if you want to change the position of your UILabel, just change labelPosition and then set daLabel.frame to the modified labelPosition. For example:

- (void)viewDidLoad {
    [super viewDidLoad];
    NewClass *anotherClass = [[NewClass alloc] init];
    [anotherClass test:self];

}

- (void)test:(MainViewController *)mvc {
    CGRect labelPosition = mvc.daLabel.frame;
    NSLog(@"POSITION: %f", labelPosition.origin.x); // Returns 0.000000
    labelPosition.origin.x = 50;
    mvc.daLabel.frame = labelPosition;  // Now moved to 50.000000
}

Upvotes: 5

Related Questions