Iphone 如何将外部链接提供给UIButton?是否可能?

Iphone 如何将外部链接提供给UIButton?是否可能?,iphone,Iphone,我的UIButton名称为“Buy now”。如果任何人点击该按钮,外部链接应在safari浏览器中打开。我如何实现这一点?创建一个按钮,并将其指定给使用该链接打开safari的选择器 基本示例: 制作一个UIButton UIButton *button = [[UIButton alloc] initWithFrame:...]; [button addTarget:self action:@selector(someMethod) forControlEvents:UIControlEve

我的UIButton名称为“Buy now”。如果任何人点击该按钮,外部链接应在safari浏览器中打开。我如何实现这一点?

创建一个按钮,并将其指定给使用该链接打开safari的选择器

基本示例:

制作一个UIButton

UIButton *button = [[UIButton alloc] initWithFrame:...];
[button addTarget:self action:@selector(someMethod) forControlEvents:UIControlEventTouchUpInside];
然后选择打开URL的方法

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

别忘了给你的按钮一个合适的框架和标题,并把它添加到你的视图中。

这很简单。为按钮设置
目标
选择器
,然后在
选择器
内调用safari打开链接

调用Safari的代码:

目标-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")!)
UIApplication.shared.openURL(URL(string: "https://www.google.co.uk")!)
Swift 3.x

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

openURL
已从iOS 10中弃用,改为使用以下内容

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

在Swift中:
UIApplication.sharedApplication().openURL(NSURL(字符串):https://www.google.com)!