Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios Swift-如何使UILabel像标签一样可点击并区分相同的文本?_Ios_Arrays_Swift_String_Dictionary - Fatal编程技术网

Ios Swift-如何使UILabel像标签一样可点击并区分相同的文本?

Ios Swift-如何使UILabel像标签一样可点击并区分相同的文本?,ios,arrays,swift,string,dictionary,Ios,Arrays,Swift,String,Dictionary,我有一个UIlabel,它的文本如下所示 label.text = "#fun #fun #google #youtube" 我想使UILabel可点击并打开其url。 我还制作字典来设置它的键和值。 var dic:[String:String] = ["https://www.yahoo.com.tw/" :"fun", "https://www.facebook.com.tw/":"fun",

我有一个UIlabel,它的文本如下所示

label.text = "#fun #fun #google #youtube"
我想使UILabel可点击并打开其url。

我还制作字典来设置它的键和值。

var dic:[String:String] = ["https://www.yahoo.com.tw/"   :"fun",
                           "https://www.facebook.com.tw/":"fun",
                           "https://www.google.com.tw/"  :"Google",
                           "https://www.youtube.com/"    :"Youtube"
                          ]  
//How about change it's type to array?
var arr:[[String:String]] = [["https://www.yahoo.com.tw/"   :"fun"],
                             ["https://www.facebook.com.tw/":"fun"],
                             ["https://www.google.com.tw/"  :"Google"],
                             ["https://www.youtube.com/"    :"Youtube"]
                            ] 
当我点击“乐趣”时,如何将“乐趣”分离以加载不同的url?

我使用第三个库ActiveLabel.swift实现UILabel可点击

label.handleHashtagTap({ (string) in 
    //do something.

    let keys = self.dic.allKeys(forValue: "#\(string) ")        
    print("--> keys: \(keys)")

})

extension Dictionary where Value: Equatable {
    func allKeys(forValue val: Value) -> [Key] {
        return self.filter { $1 == val }.map { $0.0 }
    }
}

使用字典数组,然后执行以下操作

let dataArray = [["https://www.yahoo.com.tw/"   :"fun"],
                         ["https://www.facebook.com.tw/":"fun"],
                         ["https://www.google.com.tw/"  :"Google"],
                         ["https://www.youtube.com/"    :"Youtube"]
                        ] 
您可以运行for循环来显示标签上的所有值:

for i in 0..<dataArray.count{
    let label = UILabel()
    label.tag = i
    for (key,value) in dataArray[i]{
        print(key, value)
        label.text = "#\(value)"
    }
    // then add tap gesture to that label
}

对于0中的i..使用字典数组,然后执行以下操作

let dataArray = [["https://www.yahoo.com.tw/"   :"fun"],
                         ["https://www.facebook.com.tw/":"fun"],
                         ["https://www.google.com.tw/"  :"Google"],
                         ["https://www.youtube.com/"    :"Youtube"]
                        ] 
您可以运行for循环来显示标签上的所有值:

for i in 0..<dataArray.count{
    let label = UILabel()
    label.tag = i
    for (key,value) in dataArray[i]{
        print(key, value)
        label.text = "#\(value)"
    }
    // then add tap gesture to that label
}

对于0中的i..您可以使用UICollectionView。为所有单词创建单元格。当您有4个单词时,使用4个单元格并根据垂直或水平方向给出UICollectionView方向。它还可以帮助您归档伟大的布局,您可以自定义所需的方式。

您可以使用UICollectionView。为所有单词创建单元格。当您有4个单词时,使用4个单元格并根据垂直或水平方向给出UICollectionView方向。它还可以帮助您归档伟大的布局,您可以自定义所需的方式。

您可以使用
UITextView
和包含链接的标记的
nsattributetedstring
来实现所描述的内容

您可以查看下面的示例,也可以使用Xcode将其复制/粘贴到新的游乐场中进行测试

如果要使用与默认操作不同的URL,还可以覆盖
UITextView
的默认URL交互行为

//: A UIKit based Playground for presenting user interface

import UIKit
import PlaygroundSupport

class MyViewController : UIViewController, UITextViewDelegate {

    // Assign a webView to this to override the default url interaction from the tagView
    var webView: UIWebView?

    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {

        // Check if a webView is set to be used to load URLs
        guard let webView = webView else {

            // Proceeds with default url interaction if no webview is assigned
            return true
        }

        // Load URL into the webview instead
        webView.loadRequest(URLRequest(url: URL))

        // Stops the default url interaction and uses the webView instead
        return false
    }

    override func loadView() {
        let view = UIView()
        view.backgroundColor = .white

        let tagView = UITextView()
        // Disable editing of the UITextView, this stops users from changing the UITextView content
        tagView.isEditable = false
        // Make self handle events raised by the tagView, this is required to receive the shouldInteractWith URL event
        tagView.delegate = self

        tagView.frame = CGRect(x: 100, y: 200, width: 200, height: 20)

        let dic:[String:String] = ["https://www.yahoo.com.tw/"   :"fun",
                                   "https://www.facebook.com.tw/":"fun",
                                   "https://www.google.com.tw/"  :"Google",
                                   "https://www.youtube.com/"    :"Youtube"
        ]

        let attributedString = NSMutableAttributedString()

        // Iterate through the dictionary containing tags with links
        // and create a NSAttributedString for every tag
        for (link, tag) in dic {

            // Skip tags that have a malformed link
            guard let url = URL(string: link) else { continue }

            // Create the NSAttributedString with the tag and link
            let tagString = NSAttributedString(string: "#\(tag) ", attributes: [NSAttributedStringKey.link: url])

            attributedString.append(tagString)
        }

        // Set the tags string to the tagView
        tagView.attributedText = attributedString

        view.addSubview(tagView)
        self.view = view
    }
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
// Enjoy your tags with links

您可以通过使用
UITextView
和包含带有链接的标记的
nsattributed字符串来实现所描述的内容

您可以查看下面的示例,也可以使用Xcode将其复制/粘贴到新的游乐场中进行测试

如果要使用与默认操作不同的URL,还可以覆盖
UITextView
的默认URL交互行为

//: A UIKit based Playground for presenting user interface

import UIKit
import PlaygroundSupport

class MyViewController : UIViewController, UITextViewDelegate {

    // Assign a webView to this to override the default url interaction from the tagView
    var webView: UIWebView?

    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {

        // Check if a webView is set to be used to load URLs
        guard let webView = webView else {

            // Proceeds with default url interaction if no webview is assigned
            return true
        }

        // Load URL into the webview instead
        webView.loadRequest(URLRequest(url: URL))

        // Stops the default url interaction and uses the webView instead
        return false
    }

    override func loadView() {
        let view = UIView()
        view.backgroundColor = .white

        let tagView = UITextView()
        // Disable editing of the UITextView, this stops users from changing the UITextView content
        tagView.isEditable = false
        // Make self handle events raised by the tagView, this is required to receive the shouldInteractWith URL event
        tagView.delegate = self

        tagView.frame = CGRect(x: 100, y: 200, width: 200, height: 20)

        let dic:[String:String] = ["https://www.yahoo.com.tw/"   :"fun",
                                   "https://www.facebook.com.tw/":"fun",
                                   "https://www.google.com.tw/"  :"Google",
                                   "https://www.youtube.com/"    :"Youtube"
        ]

        let attributedString = NSMutableAttributedString()

        // Iterate through the dictionary containing tags with links
        // and create a NSAttributedString for every tag
        for (link, tag) in dic {

            // Skip tags that have a malformed link
            guard let url = URL(string: link) else { continue }

            // Create the NSAttributedString with the tag and link
            let tagString = NSAttributedString(string: "#\(tag) ", attributes: [NSAttributedStringKey.link: url])

            attributedString.append(tagString)
        }

        // Set the tags string to the tagView
        tagView.attributedText = attributedString

        view.addSubview(tagView)
        self.view = view
    }
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
// Enjoy your tags with links

您可以将
NSAttributedString
documentType
html
一起使用。请参考此示例:

class ViewController: UIViewController, UITextViewDelegate {

    @IBOutlet weak var textView: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let attrText = htmlAttributedString("<span style=\"font-family: 'NotoSans'; font-size: 16; color: #666666\">ĐÃ CÀO TRÚNG <a href=\"google.com.vn\">Link here</a></span>")
        textView.delegate = self
        textView.isEditable = false
        textView.attributedText = attrText
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        print(URL.absoluteString)
        return false
    }

    func htmlAttributedString(_ templateString: String) -> NSAttributedString? {
        do {
            if let data = templateString.data(using: .unicode, allowLossyConversion: true) {
                let options = [
                    NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html,
                    ]
                let str = try NSAttributedString(data: data, options: options, documentAttributes: nil)
                return str
            }
        } catch let error {
            print(error.localizedDescription)
        }


        return nil
    }

}
类ViewController:UIViewController、UITextViewDelegate{
@IBOutlet弱var textView:UITextView!
重写func viewDidLoad(){
super.viewDidLoad()
//加载视图后,通常从nib执行任何其他设置。
让attrText=htmlAttributedString(“ĐÃCÀO TRÚNG”)
textView.delegate=self
textView.isEditable=false
textView.attributedText=属性文本
}
重写函数didReceiveMemoryWarning(){
超级。我收到了记忆警告()
//处置所有可以重新创建的资源。
}
func textView(textView:UITextView,应与URL:URL交互,字符范围:NSRange,交互:UITextItemInteraction)->Bool{
打印(URL.absoluteString)
返回错误
}
func htmlAttributedString(uTemplateString:String)->NSAttributedString{
做{
如果let data=templateString.data(使用:.unicode,allowLossyConversion:true){
让选项=[
NSAttributedString.DocumentReadingOptionKey.documentType:NSAttributedString.documentType.html,
]
让str=try NSAttributedString(数据:数据,选项:选项,文档属性:nil)
返回str
}
}捕捉错误{
打印(错误。本地化描述)
}
归零
}
}
使用html documentType,您可以自由设置文本样式。此外,要检测单击了哪个url,可以使用
func textView(\utextview:UITextView,应与url:url交互,在字符范围内:NSRange,交互:UITextItemInteraction)->Bool
从UITextView委托


要消除链接单击延迟,您还可以参考以下要点:

您可以将
NSAttributedString
documentType
html
一起使用。请参考此示例:

class ViewController: UIViewController, UITextViewDelegate {

    @IBOutlet weak var textView: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let attrText = htmlAttributedString("<span style=\"font-family: 'NotoSans'; font-size: 16; color: #666666\">ĐÃ CÀO TRÚNG <a href=\"google.com.vn\">Link here</a></span>")
        textView.delegate = self
        textView.isEditable = false
        textView.attributedText = attrText
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        print(URL.absoluteString)
        return false
    }

    func htmlAttributedString(_ templateString: String) -> NSAttributedString? {
        do {
            if let data = templateString.data(using: .unicode, allowLossyConversion: true) {
                let options = [
                    NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html,
                    ]
                let str = try NSAttributedString(data: data, options: options, documentAttributes: nil)
                return str
            }
        } catch let error {
            print(error.localizedDescription)
        }


        return nil
    }

}
类ViewController:UIViewController、UITextViewDelegate{
@IBOutlet弱var textView:UITextView!
重写func viewDidLoad(){
super.viewDidLoad()
//加载视图后,通常从nib执行任何其他设置。
让attrText=htmlAttributedString(“ĐÃCÀO TRÚNG”)
textView.delegate=self
textView.isEditable=false
textView.attributedText=属性文本
}
重写函数didReceiveMemoryWarning(){
超级。我收到了记忆警告()
//处置所有可以重新创建的资源。
}
func textView(textView:UITextView,应与URL:URL交互,字符范围:NSRange,交互:UITextItemInteraction)->Bool{
打印(URL.absoluteString)
返回错误
}
func htmlAttributedString(uTemplateString:String)->NSAttributedString{
做{
如果let data=templateString.data(使用:.unicode,allowLossyConversion:true){
让选项=[
NSAttributedString.DocumentReadingOptionKey.documentType:NSAttributedString.documentType.html,
]
让str=try NSAttributedString(数据:数据,选项:选项,文档属性:nil)
返回str
}
}捕捉错误{
打印(错误。本地化描述)
}
归零
}
}
使用html documentType,您可以自由设置文本样式。此外,要检测单击了哪个url,可以使用
func textView(\utextview:UITextView,应与url:url交互,在字符范围内:NSRange,交互:UITextItemInteraction)->Bool
从UITextView委托


要消除链接点击延迟,您还可以参考以下要点:

请显示您迄今为止所做的尝试。抱歉,但我不知道如何区分“#乐趣”。如果您使用
UITextField