user3576592
user3576592

Reputation:

Swift 2 Table View Cell with Hyperlink

I've created a UITableView with different Sections and cells like: "Follow us on Instagram" or "Like us on Facebook". This cells should have a link to each page. I tried this:

@IBAction func WebLink(sender: AnyObject) {
if let url = NSURL(string: "http://...") {
    UIApplication.sharedApplication().openURL(url)
}
}

But i can't link the @IBAction with the Cell...

It should look like this and on every Cell should be a Hyperlink.

enter image description here

Upvotes: 0

Views: 1501

Answers (2)

KFDoom
KFDoom

Reputation: 634

I'm not finding anything that would allow us to do so with a simple label. But there is a library available that does so in github. It seems you can't do so with a simple label in Swift. However, there is a library called TTTAttributedLabel that I think does what you're looking for. Here's a link to the library: https://github.com/TTTAttributedLabel/TTTAttributedLabel

@IBOutlet var exampleLabel: TTTAttributedLabel!

    //...

let exampleString: NSString = "My super cool link"
exampleLabel.delegate = self
exampleLabel.text = exampleString as String
var range : NSRange = exampleString.rangeOfString("link")
exampleLabel.addLinkToURL(NSURL(string: "http://www.stackoverflow.com")!, withRange: range)

func attributedLabel(label: TTTAttributedLabel!, didSelectLinkWithURL url: NSURL!) {
        UIApplication.sharedApplication().openURL(url)
}

Side note: Did not ever imagine I'd miss Objective-C. I'll update with a Swift 3.0 answer if this is what you were looking for.

Upvotes: 1

Alessandro Ornano
Alessandro Ornano

Reputation: 35392

You can directly use:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
     let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!
     // launch your func WebLink with the currentCell
     ...
}

Upvotes: 2

Related Questions