如何创建一个“超链接”与Swift? [英] How can I create a "hyperlink" with Swift?

查看:341
本文介绍了如何创建一个“超链接”与Swift?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使单独的文本 UILabel 可点击。我在寻找的是在网络开发中通常被称为超链接。

I'm trying to make separate pieces of text UILabels clickable. What I'm looking for is commonly known as a hyperlink in web development.

<a href="//example.com">Link 1</a>
<a href="//example.com/example">Link 2</a>
<a href="//example.com/other_example">Link 3</a>

每个 a 标签是自己的 UILabel ,当单击标签之间的文本时,理想情况下将打开Safari到指定的 href

Each a tag is its own UILabel, and it would ideally open Safari to the specified href when the text between the tags is clicked.

我发现了一些关于如何在Objective-C中做这种事情的资源,但是它们似乎都不必要地复杂,并且不能很好地转换为Swift(他们适合一个目标-C组织结构,在Swift中不能很好地工作,违背了推荐的语言使用方式)。

I've found a bevy of resources on how to do this sort of thing in Objective-C, but they all seem unnecessarily complicated and don't translate well to Swift (they fit an Objective-C organizational structure that doesn't work well in Swift and goes against the recommended way of using the language).

这里有几个:

  • How to add hyperlink in iPhone app?
  • How to make a clickable link inside a NSTextField and Cocoa
  • Text as Hyperlink in Objective-C

如果我有一个3 UILabel


项目1

Item 1

项目2

项目3

那么什么是最好的Swift-y方式,使每个项目打开到一个不同的URL在Safari?

then what would be the best "Swift-y" way to make each item open to a different URL in Safari?

可以为每个按钮创建单独的按钮,但是 UILabel 是以编程方式填充的,因此我认为让文本响应敲击可能是一个更好的选择。

I could create separate buttons for each, but the UILabels are programmatically populated, so I was thinking that making the text respond to taps might be a better option.

推荐答案

The one方法将类似于以下内容。

假设是:

The One approach would be something like the following.
The assumptions are:


  • self.urls是一个字符串数组,其中包含与每个 UILabel 关联的网址。

  • 每个 UILabel 标签已设置为数组中的相应索引

  • labelTapped:设置为标签的 touchUpInside 处理程序。



    • self.urls is a string array containing the urls associated with each UILabel.
    • Each UILabel tag has been set to the corresponding index in the array
    • labelTapped: is set as the touchUpInside handler for the labels.
    import Foundation
    import UIKit
    
    class urltest {
    
        var urls:[String]
    
        init() {
            self.urls=[String]()  // Load URLs into here
        }
    
        @IBAction func labelTapped(sender:UILabel!) {
    
            let urlIndex=sender.tag;
            if (urlIndex >= 0 && urlIndex < self.urls.count) {
               self.openUrl(self.urls[urlIndex]);
            }
    
        }
    
        func openUrl(url:String!) {
    
            let targetURL=NSURL.URLWithString(url)
    
            let application=UIApplication.sharedApplication()
    
            application.openURL(targetURL);
    
        }
    }
    

    这篇关于如何创建一个“超链接”与Swift?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆