以编程方式将按钮添加到uitableview单元

时间:2020-06-28 03:43:49

标签: swift uitableview button cell didselectrowatindexpath

我只希望我的代码在每个带有文本的表格视图单元格中产生一个按钮。按下按钮时,请打个招呼。每个单元格中应该都有一个按钮。我希望做到这一点并编写代码,而根本不使用情节提要。该类应保留为uiview控制器,并且不得更改。

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

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

    override func viewDidLoad() {
        super.viewDidLoad()

        myTableView.register(UITableViewCell.self, forCellReuseIdentifier: "MyCell")
        myTableView.dataSource = self
        myTableView.delegate = self
        
        
        
        self.view.addSubview(myTableView)
        myTableView.translatesAutoresizingMaskIntoConstraints = false
        
        
        
        NSLayoutConstraint.activate([

            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
    }
}

2 个答案:

答案 0 :(得分:0)

您可以将UIButton添加到UITableViewCell中,只需将其添加到cellForRow方法中,如下所示:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath)
    let button = UIButton()
    button.setTitle("\(myArray[indexPath.row])", for: .normal)
    button.center = cell.center
    cell.addSubview(button)
    return cell
}

尽管以上方法可行,但不建议这样做。您可能应该为UITableViewCell创建一个自定义类,并将其用作单元格,如下所示:

class MyCustomCell: UITableViewCell {
    let button = UIButton()
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        addSubview(button)
        // do layout setup here
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

用法:

override func viewDidLoad() {
    super.viewDidLoad()
    myTableView.register(MyCustomCell.self, forCellReuseIdentifier: "MyCell")
    //...
}
//...
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath) as! MyCustomCell
    cell.button.setTitle("\(myArray[indexPath.row])", for: .normal)
    return cell
}

答案 1 :(得分:0)

创建UITableViewcell的子类-

class MyCell: UITableViewCell {
    
    var buttonTapCallback: () -> ()  = { }
    
    let button: UIButton = {
        let btn = UIButton()
        btn.setTitle("Button", for: .normal)
        btn.backgroundColor = .systemPink
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        return btn
    }()
    
    let label: UILabel = {
       let lbl = UILabel()
        lbl.font = UIFont.systemFont(ofSize: 16)
        lbl.textColor = .systemPink
       return lbl
    }()
    
    @objc func didTapButton() {
        buttonTapCallback()
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        //Add button
        contentView.addSubview(button)
        button.addTarget(self, action: #selector(didTapButton), for: .touchUpInside)
        
        //Set constraints as per your requirements
        button.translatesAutoresizingMaskIntoConstraints = false
        button.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 20).isActive = true
        button.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 10).isActive = true
        button.widthAnchor.constraint(equalToConstant: 100).isActive = true
        button.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -10).isActive = true
        
        //Add label
        contentView.addSubview(label)
        //Set constraints as per your requirements
        label.translatesAutoresizingMaskIntoConstraints = false
        label.leadingAnchor.constraint(equalTo: button.trailingAnchor, constant: 20).isActive = true
        label.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 10).isActive = true
        label.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -10).isActive = true
        label.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -10).isActive = true
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

现在在您的视图控制器中注册该单元格-

myTableView.register(MyCell.self, forCellReuseIdentifier: "MyCell")

现在使用cellForRowAt方法加载此单元格-

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath) as! MyCell
        cell.label.text = ""
        cell.buttonTapCallback = {
            cell.label.text = "Hi"
        }
        return cell
    }