如何创建“超链接"?与斯威夫特? [英] How can I create a "hyperlink" with Swift?

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

问题描述

我正在尝试使 UILabel 的单独文本片段可点击.我正在寻找的内容通常被称为 Web 开发中的超链接.

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(它们适合 Objective-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).

这里有一些:

如果我有 3 个 UILabels,

If I had a 3 UILabels,

项目 1

项目 2

项目 3

那么最好的Swift-y"是什么?如何让每个项目在 Safari 中打开到不同的 URL?

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.

推荐答案

One 方法类似于以下内容.
假设是:

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

  • self.urls 是一个字符串数组,包含与每个 UILabel 关联的 url.
  • 每个UILabel tag 都被设置为数组中对应的索引
  • 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);

    }
}

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

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