Add button to uitableview cell programmatically

I just want my code to produce a button in every table view cell that has text. When the button is press just have it say hi. That is all thanks.

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    private let myArray: NSArray = ["First","Second","Third"]
     var myTableView =  UITableView()

    override func viewDidLoad() {

        myTableView.register(UITableViewCell.self, forCellReuseIdentifier: "MyCell")
        myTableView.dataSource = self
        myTableView.delegate = self
        myTableView.translatesAutoresizingMaskIntoConstraints = false

            myTableView.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.90),
            myTableView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 1),
            myTableView.topAnchor.constraint(equalTo: view.topAnchor),
            myTableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),


    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("Num: \(indexPath.row)")
        print("Value: \(myArray[indexPath.row])")

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return myArray.count

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath as IndexPath)
        cell.textLabel!.text = "\(myArray[indexPath.row])"
        return cell

@timswift Do you still have issues with this?

This topic was automatically closed after 166 days. New replies are no longer allowed.