bardockyo
bardockyo

Reputation: 1435

passing a value to a button in xcode

I am seeing if there is a way to pass a variable to a button in xcode. I have a web link that I am retrieving from an API that I am storing to a NSString. I am just wondering if there is a way to pass that to a button so that when it is clicked it can follow the link accordingly.

Upvotes: 0

Views: 225

Answers (2)

pIkEL
pIkEL

Reputation: 571

You can just subclass the UIBUtton and add any properties/variables that you like/need. From your description I would use a NSURL instead of NSString...

Create a new UIButton subclass, in your .h file write:

#import <UIKit/UIKit.h>
@interface MyButton : UIButton
{
     NSURL* buttonUrl;
}
@property (nonatomic, retain) NSURL* buttonUrl;
@end

and in the .m file simply:

#import "MyButton.h"
@implementation MyButton
@synthesize buttonUrl;
@end

Then in your ViewController: (don't forget to #import "MyButton.h)

MyButton *theButton = [[MyButton alloc] initWithFrame:someframe];
[theButton addTarget:self action:@selector(buttonPushed:) forControlEvents:UIControlEventTouchUpInside];
theButton.buttonUrl = [NSURL URLWithString:apiString];
[self.view addSubView:theButton];
[theButton release];

... And then you can get the URL again when the button was pushed as:

-(void)buttonPushed:(id)sender{
    NSURL* theUrl = [(MyButton*)sender getButtonUrl];
}

Upvotes: 0

Hermann Klecker
Hermann Klecker

Reputation: 14068

You store that URL lcoally in some ivar or property. You assign an action to your button as usual. The action is nothing less than a method of your view controller. Within that method you execute that link.

This is how you can "follow" your link:

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.klecker.de"]];

In your case you would use an NSString variable instead of the constant that I am using in this example.

Upvotes: 2

Related Questions