我想创建一个带有动作按钮的自定义XIB表视图单元格,该按钮可以设置到新的视图控制器。
到目前为止,我已经创建了一个带有按钮(timeButton)的自定义XIB单元格(TaskListCell ),并将TaskListCell注册到TaskListViewController。对于tableView(_:cellForRowAt :),我为timeButton添加了标签,并添加了addTarget (_:action:for :)以在点击timeButton时做出响应。但是,我收到此错误消息:线程1:“-[[Sprints.TaskListCellPressedTimeButton:]:无法识别的选择器已发送到实例0x105311560”
这是定制的XIB单元文件:
class TaskListCell: UITableViewCell {
@IBOutlet weak var nameField: UITextField!
@IBOutlet weak var timeButton: UIButton!
@IBAction func pressedTimeButton(_ sender: UIButton) {
}
override func awakeFromNib() {
}
override func setSelected(_ selected: Bool, animated: Bool) {
}
}
这是在表视图中显示自定义单元格的ViewController:
class TaskListViewController: UIViewController {
// MARK: - Outlet Variables
@IBOutlet weak var taskList: SelfSizedTableView!
...
// MARK: - Instance Variables
var taskData = [TaskData]()
var taskCount: Int = 1
...
// MARK: - View Controller Methods
override func viewDidLoad() {
super.viewDidLoad()
// Register TaskListCell.xib file
let taskCellNib = UINib(nibName: "TaskCell", bundle: nil)
taskList.register(taskCellNib, forCellReuseIdentifier: "taskCell")
...
// Connect table view's dataSource and delegate to current view controller
taskList.delegate = self
taskList.dataSource = self
}
// MARK: - Action Methods
// Adds new cell in Table View
@IBAction func pressedAddTask(_ sender: UIButton) {
taskCount += 1
taskList.reloadData()
taskList.scrollToRow(at: IndexPath(row: taskCount-1, section: 0), at: .bottom, animated: true)
}
// MARK: - Methods
// Segues to SelectTime screen when timeButton is pressed
@objc func pressedTimeButton(_ sender: UIButton) {
let destination = SelectTimeViewController()
navigationController?.pushViewController(destination, animated: true)
}
}
extension TaskListViewController: UITableViewDataSource {
// Return the number of rows in table view
func tableView(_ tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return taskCount
}
// Return the cell to insert in table view
func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "taskCell", for: indexPath) as! TaskListCell
// Fatal error for next line: "Unexpectedly found nil while implicitly unwrapping an Optional value"
cell.timeButton.tag = indexPath.row
cell.timeButton.addTarget(self, action: #selector(pressedTimeButton(_:)), for: .touchUpInside)
return cell
}
}
extension TaskListViewController: UITableViewDelegate {
}
从您的单元格检查IBAction实例是否正在被调用。删除此功能,它将起作用
@IBAction func pressedTimeButton(_ sender: UIButton) {
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句