简体   繁体   English

UITableViewCell addTarget 中的按钮不起作用

[英]Button in UITableViewCell addTarget does not work

In my project I have table view with cells with 3 buttons.在我的项目中,我有带有 3 个按钮的单元格的表格视图。 When I added target action for them, it did not work.当我为他们添加目标操作时,它不起作用。

To avoid bad interaction with other items I created a clean project and tried to addTarget to button in TableViewCell .为了避免与其他项目的不良交互,我创建了一个干净的项目并尝试将addTarget添加到TableViewCell中的按钮。 Even here, it did not work.即使在这里,它也不起作用。 In this project I set one button to each row.在这个项目中,我为每一行设置了一个按钮。

addTarget method should call presentWebBrowser method. addTarget方法应该调用presentWebBrowser方法。 But doesn't.但是没有。 Any ideas?有任何想法吗?

Here is my code:这是我的代码:

import UIKit

class TableViewController: UITableViewController {

let array = ["button1","button2","button3"]

override func viewDidLoad() {
    super.viewDidLoad()
tableView.register(MyCell.self, forCellReuseIdentifier: "cellID")

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK: - Table view data source



override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return array.count
}


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cellID", for: indexPath) as! MyCell

    return cell

}

}

class MyCell: UITableViewCell {



var button: UIButton = {
    let button = UIButton(type: UIButtonType.system)
    button.setTitle("Button", for: UIControlState.normal)
     button.addTarget(self, action: #selector(presentWebBrowser), for: .touchUpInside)

    // button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 8)

    return button
}()


override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)

    addSubview(button)
    button.translatesAutoresizingMaskIntoConstraints = false
    button.topAnchor.constraint(equalTo: topAnchor).isActive = true
    button.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
    button.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true



}


required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

@objc func presentWebBrowser(sender: UIButton!) {
    print("tapped")

}



}

First remove the add target in lazy initialization of button variable先去掉按钮变量惰性初始化中的add target

var button: UIButton = {
    let button = UIButton(type: UIButtonType.system)
    button.setTitle("Button", for: UIControlState.normal)
    return button
}()

Modify your code in init as将 init 中的代码修改为

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    addSubview(button)
    button.addTarget(self, action: #selector(presentWebBrowser), for: .touchUpInside)
    button.translatesAutoresizingMaskIntoConstraints = false
    button.topAnchor.constraint(equalTo: topAnchor).isActive = true
    button.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
    button.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true

}

Note use of addTarget on button outside the lazy initialization.注意在惰性初始化之外在button上使用 addTarget。

Must be in a lazy declaration or after the initializer:必须在惰性声明中或在初始化程序之后:

lazy var button: UIButton = {
   let button = UIButton(type: .system)
   button.setTitle("Button", for: UIControlState.normal)
   button.addTarget(self, action: #selector(presentWebBrowser), for: .touchUpInside)
   return button
}()

This is because the target view must finish initialization before a selector can be bound to it.这是因为目标视图必须在选择器绑定到它之前完成初始化。

the solution is very simple.解决方法很简单。 add below code in init function:init函数中添加以下代码:

button.addTarget(self, action: #selector(presentWebBrowser), for: .touchUpInside)

that's it!而已!

Well, maybe I can help with what worked for me so far:好吧,也许我可以帮助解决目前对我有用的问题:

Create UIButton创建 UIButton

lazy var _actionButton: UIButton = {
        let button = UIButton()
        button.setImage(UIImage(named: "reset"), for: .normal)
        button.translatesAutoresizingMaskIntoConstraints = false
        button.addTarget(self, action: #selector(handleAction), for: .touchUpInside)
        return button
    }()

@objc Function @objc 函数

@objc func handleAction(){
    print("test reset via action button...")
}

In tableviewcell class, precisely in init Method, instead of using:在 tableviewcell 类中,正是在init方法中,而不是使用:

addsubview(_actionButton)

use采用

contentView.addSubview(_actionButton)

Cheers干杯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM