为什么 UIButton 上的点击事件不会触发?

时间:2021-01-20 05:06:53

标签: uitableview

为什么不调用 clickDone,我尝试了两种注册事件的方式。都没有用。

import UIKit

class ViewController: UIViewController {

    let myTableView: UITableView = {
        let _myTableView = UITableView()
        return _myTableView
    }()
    
    override func viewDidLoad() {
        myTableView.register(MyTableViewCell.self, forCellReuseIdentifier: "Cell")
        myTableView.dataSource = self
        myTableView.delegate = self
        myTableView.translatesAutoresizingMaskIntoConstraints = false
        
        view.addSubview(myTableView)
        NSLayoutConstraint.activate([
            myTableView.topAnchor.constraint(equalTo: self.view.topAnchor),
            myTableView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor),
            
            myTableView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
            
            myTableView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
            
        ])
        super.viewDidLoad()
    }
}


extension ViewController: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 100
    }
    
    @objc func clickDone(_ sender: Any) {
        NSLog("I am clicked")
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! MyTableViewCell
        
        cell.clickButton.addTarget(self, action: #selector(clickDone(_:)), for: .touchUpInside)
        return cell

    }
    
}


class MyTableViewCell: UITableViewCell {
    let clickButton: UIButton = {
        let _b = UIButton()
        _b.setTitle("Click", for: .normal)
        
        return _b
    }()
    
    @objc func clickDone(_ sender: Any) {
        NSLog("I am clicked")
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
     super.init(style: style, reuseIdentifier: reuseIdentifier)
        addSubview(clickButton)
        
        clickButton.translatesAutoresizingMaskIntoConstraints = false
        
        NSLayoutConstraint.activate([
            clickButton.topAnchor.constraint(equalTo: topAnchor),
            
            clickButton.bottomAnchor.constraint(equalTo: bottomAnchor),
            clickButton.leadingAnchor.constraint(equalTo: leadingAnchor),
            clickButton.trailingAnchor.constraint(equalTo: trailingAnchor),
            
        ])
        
        clickButton.addTarget(self, action: #selector(clickDone(_:)), for: .touchUpInside)
        
    }
    
    required init?(coder aDecoder: NSCoder) {
     fatalError("init(coder:) has not been implemented")
     }
}

0 个答案:

没有答案
相关问题