How can I create a “hyperlink” with Swift?

前端 未结 3 796
伪装坚强ぢ
伪装坚强ぢ 2021-01-07 03:53

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.



        
3条回答
  •  执念已碎
    2021-01-07 04:25

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

    • 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);
    
        }
    }
    

提交回复
热议问题