Kyle Greenlaw
Kyle Greenlaw

Reputation: 737

Display text from tap counter on two views

So I have my app and I have a view with a tap counter and the displaying label. I would like it to display the text on the main view (it does now) but also on a second view.

So how could i display the text on the other view. If more details needed, please email.

STEPS TO REPRODUCE FOR TAP COUNTER The .h file:

@interface Level1 : UIViewController {

int counter;

IBOutlet UILabel *count;

}

-(IBAction)plus;

@property (assign) int counter;

@end

The .m file:

@synthesize counter;

- (void) viewDidLoad {

counter=1;

count.text = @"0";

[super viewDidLoad];
}

-(IBAction)plus {

counter=counter + 1;

count.text = [NSString stringWithFormat:@"%i",counter];
}

@end 

Thanks in advance

Upvotes: 0

Views: 109

Answers (2)

Theepan Karthigesan
Theepan Karthigesan

Reputation: 603

Here you can use delegate to pass data to en another view. When you load the second view probably via the first view, you can set your first view as the datasource.

http://www.youtube.com/watch?v=e5l0QOyxZvI

You can also use the notification center to send message to another view.

Upvotes: 0

Tomasz Zabłocki
Tomasz Zabłocki

Reputation: 1326

You can create model with your counter value which will be shared among both views.

Model is usually created with singleton pattern. In this case it could be done this way:

your .h file:

@interface CounterModel
@property (assign) NSInteger counter;// atomic
+ (id)sharedInstance;
- (void)increment;
@end

your .m file:

@implementation CounterModel
@synthesize counter;

- (id)init
{
    if (self = [super init])
    {
    }
    return self;
}

+ (id)sharedInstance
{
    static CounterModel *instance = nil;
    if (instance == nil)
    {
        instance = [[CounterModel alloc] init];
    }
    return instance;
}

- (void)increment
{
    counter++;
}

@end

Then from one view controller you can call:

[[CounterModel sharedInstance] increment];

and from second you can read this updated value by calling:

[[CounterModel sharedInstance] counter];

To achieve what you want you could set UILabel value read from model's counter value in viewWillAppear method.

Upvotes: 1

Related Questions