[英]“Use of unresolved indentifier 'self'” with button.addTarget
[英]Swift 3 button.addTarget not working on all table cells
我創建了一個應用程序,允許用戶存儲針對評論的各種語音記錄。 當我顯示此表時,數據將使用以下代碼填充:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let row = (indexPath as NSIndexPath).item
let cell = tableView.dequeueReusableCell(withIdentifier: "voiceRecordingCell", for: indexPath) as! VoiceRecordingTableViewCell
let voiceRecording = self.voiceRecordings[row] as! NSDictionary
let isoFormatter = DateFormatter()
isoFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'.000Z'"
let createdAt = isoFormatter.date(from: voiceRecording["created_at"] as! String)
self.recordingIndexPaths.insert(indexPath, at: row)
cell.recording = voiceRecording
cell.date.text = getDateFormatter("dd-MM-y").string(from: createdAt!)
cell.time.text = getDateFormatter("HH:mm").string(from: createdAt!)
cell.length.text = voiceRecording["length"] as? String
cell.location.text = voiceRecording["location"] as? String
let audioPlayerController = self.storyboard?.instantiateViewController(withIdentifier: "AudioPlayerController") as! AudioPlayerController
audioPlayerController.voiceRecording = voiceRecording
cell.audioPlayer.addSubview(audioPlayerController.view)
self.addChildViewController(audioPlayerController)
audioPlayerController.didMove(toParentViewController: self)
cell.deleteRecordingButton.tag = row
cell.deleteRecordingButton.addTarget(self, action: #selector(deleteRecordingPressed(_:)), for: .touchUpInside)
return cell
}
單元格似乎都正確呈現,但是對於最初未隨頁面呈現的單元格,我必須向下滾動以查看,當我單擊音頻播放器控件或deleteRecordingButton
上的按鈕時,沒有任何反應,好像沒有設置addTarget
。 設置按鈕的代碼被調用並且不會產生錯誤,只是不應用於這些按鈕。
最初顯示在屏幕上的按鈕具有正確的操作,並且都可以正常工作,所以我知道這是可行的。
我真的不知道是什么原因造成的。 我曾嘗試搜索google和stackoverflow,但未找到任何內容。 對此將提供任何幫助。
---------------更新-----------
我只是嘗試在其中設置一些斷點
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
這也只能在頂部的2個單元格上調用,如果在橫向,則在頂部的單元格上調用!
由於單元一直在重復使用,因此參考丟失了。 嘗試這樣的事情:
class ButtonTableViewCell: UITableViewCell {
typealias TapClosure = () -> Void
var buttonTapped: TapClosure?
@IBAction func buttonTouchUpInside(sender: UIButton) {
buttonTapped?()
}
}
extension TestViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let cell = tableView.dequeueReusableCell(withIdentifier: "identifier", for: indexPath) as! ButtonTableViewCell
cell.buttonTapped = {
print("Button tapped")
}
return cell
}
}
還有另一個小費。 切勿在cellForRowAtIndexPath中初始化DateFormatter
。 而是在viewDidLoad或靜態結構中創建它以供重用。
終於我明白了...
發生這種情況的原因是,我使用的是帶有滾動視圖的滾動視圖,而不使用表的本機滾動功能來上下滾動表。
使用表格滾動功能時,將按鈕應用到將動作帶入視圖中的過程。 這由func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
方法處理。 但是,當您按照我原先的方式進行操作時,它最初將渲染所有單元,而屏幕外的單元將無法正常工作!
以這種方式工作有點煩人,但至少我現在知道這一點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.