开发者

How can i give the external link to UIButton?Is it possible?

I am having the UIButton name as "Buy开发者_高级运维 now".If any one touch the button,the external link should open in the safari browser.How can i achieve this?


It's easy. You set the target and selector for the button, then inside the selector, you call safari to open your link.

Code to call Safari:

Objective-C

- (void)buttonPressed {
    [[UIApplication sharedApplication] 
        openURL:[NSURL URLWithString: @"https://www.google.co.uk"]];
}

Swift 2.x

UIApplication.sharedApplication().openURL(NSURL(string: "https://www.google.co.uk")!)

Swift 3.x

UIApplication.shared.openURL(URL(string: "https://www.google.co.uk")!)


Create a button, and give it a target to a selector that opens Safari with the link.

Basic example:

Make a UIButton

UIButton *button = [[UIButton alloc] initWithFrame:...];
[button addTarget:self action:@selector(someMethod) forControlEvents:UIControlEventTouchUpInside];

Then the method to open the URL

-(void)someMethod {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString: @"http://www.google.ca"]];
}

Don't forget to give your button a proper frame and title, and to add it to your view.


- (IBAction)buyNowButtonPressed {
    NSString *s = [ NSString stringWithFormat:@"http://www.sample.com/buynowpage"];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:s]];
}


openURL is deprecated from iOS 10 and use following instead.

UIApplication *application = [UIApplication sharedApplication];
NSURL *url = [NSURL URLWithString:@"http://www.yourDomain.com"];
[application openURL:url options:@{} completionHandler:nil];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜