Open URL with a button inside a table view cell

前端 未结 3 1601
轻奢々
轻奢々 2021-01-22 11:58

I want to include a button in each table cell that opens a URL.

I\'ve created tables (using an array) with images and labels just fine, however I\'m confused how to crea

3条回答
  •  [愿得一人]
    2021-01-22 12:24

    Swift 4

    This is best way to get indexPath using touchPoint

    class YourTableViewController: UITableViewController {
    
        // ...
    
        override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "SwiftyCell", for: indexPath) as! SwiftyTableViewCell
    
            cell.label.text = "This is cell number \(indexPath.row)"
    
            // WRONG! When cells get reused, these actions will get added again! That's not what we want.
            // Of course, we could get around this by jumping through some hoops, but maybe there's a better solution...
            cell.yourButton.addTarget(self, action: #selector(self.yourButtonTapped(_:)), for: .touchUpInside)
    
            return cell
        }
    
        func yourButtonTapped(_ sender: Any?) {
            let point = tableView.convert(sender.center, from: sender.superview!)
    
            if let wantedIndexPath = tableView.indexPathForItem(at: point) {
                let cell = tableView.cellForItem(at: wantedIndexPath) as! SwiftyCell
    
            }
        }
        // ...
    
    }
    

    For more details you can follow this tutorials

提交回复
热议问题