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?
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")!)
A control that executes your custom code in response to user interactions.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With