【发布时间】:2018-08-27 07:31:24
【问题描述】:
在我的项目中,我有带有 3 个按钮的单元格的表格视图。当我为他们添加目标操作时,它不起作用。
为了避免与其他项目的不良交互,我创建了一个干净的项目并尝试通过addTarget 来按钮TableViewCell。即使在这里,它也不起作用。
在这个项目中,我为每一行设置了一个按钮。
addTarget 方法应该调用presentWebBrowser 方法。但没有。
有什么想法吗?
这是我的代码:
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")
}
}
【问题讨论】:
-
我认为上面的代码甚至不会运行,因为当使用
dequeueReusableCellinit?(coder将单元格出列并且你有一个fatalError因此应用程序将崩溃 -
Interface Builder 有什么问题(
IBAction和IBOutlet)? -
我不使用情节提要。
标签: ios swift uitableview cocoa-touch