[英]How to add an action button to a custom XIB cell?
我想創建一個帶有操作按鈕的自定義 XIB 表視圖單元格,該按鈕可以轉到新視圖 controller。
到目前為止,我創建了一個帶有按鈕(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 實例可能正在被調用。 刪除這個 function 它將工作
@IBAction func pressedTimeButton(_ sender: UIButton) {
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.