Open URL with a button inside a table view cell

前端 未结 3 1603
轻奢々
轻奢々 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:26

    Here's how I usually solve this. Create a delegate for your UITableViewCell subclass, and set the view controller owning the tableView as its delegate. Add methods for the interactions that happens inside the cell.

    protocol YourTableViewCellDelegate: class {
        func customCellDidPressUrlButton(_ yourTableCell: YourTableViewCell)
    }
    
    class YourTableViewCell: UITableViewCell {
        weak var delegate: YourTableViewCellDelegate?
    
        override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
            super.init(style: style, reuseIdentifier: reuseIdentifier)
    
            let button = UIButton()
            button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
            addSubview(button)
        }
    
        required init?(coder _: NSCoder) {
            return nil
        }
    
        @objc func buttonTapped() {
            delegate?.customCellDidPressUrlButton(self)
        }
    
    }
    

    Then, in the controller, set itself as a delegate and get the indexPath trough the proper method, indexPath(for:)

    class YourTableViewController: UITableViewController {
    
        override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! YourTableViewCell
            cell.delegate = self
            return cell
        }
    }
    
    extension YourTableViewController: YourTableViewCellDelegate {
        func customCellDidPressUrlButton(_ yourTableCell: YourTableViewCell) {
            guard let indexPath = tableView.indexPath(for: yourTableCell) else { return }
            print("Link button pressed at \(indexPath)")
        }
    }
    

    Then use that indexPath to grab the correct URL and present it from your table viewcontroller with a SFSafariViewController.

提交回复
热议问题