Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

iphone

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?

like image 772
vinay Avatar asked Aug 31 '10 05:08

vinay


People also ask

How do I open a link in SwiftUI safari?

SwiftUI gives us a dedicated Link view that looks like a button but opens a URL in Safari when pressed. It's easy enough to use – just give it a title for the button, plus a destination URL to show, like this: Link("Learn SwiftUI", destination: URL(string: "https://www.hackingwithswift.com/quick-start/swiftui")!)

What is Uibutton Swift?

A control that executes your custom code in response to user interactions.

How do I code a button in Swift?

To create a button with a string title you would start with code like this: Button("Button title") { print("Button tapped!") } Tip: The classic thing to do when you're learning a framework is to scatter print() calls around so you can see when things happen.


2 Answers

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")!)
like image 73
vodkhang Avatar answered Oct 20 '22 20:10

vodkhang


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.

like image 38
dc. Avatar answered Oct 20 '22 22:10

dc.