![](/img/trans.png)
[英]How to handle tableView cell audio play and pause button using Swift?
[英]Swift handle Play/Pause button inTableview Cell
我試圖在表格單元格中實現播放/暫停按鈕。 每個單元格都有單個按鈕,每當用戶單擊它時,都應更改按鈕圖像,還需要調用所需的功能,滾動后也應相同。
下面的代碼我正在使用
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) - > UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("productCell") as ? SepetCell
cell.onButtonTapped = {
//Do whatever you want to do when the button is tapped here
}
首先,請查看tableView Cell的每個按鈕將具有與之關聯的唯一標簽,因此,為了更新特定單元格的按鈕,您將必須在單元格中定義按鈕的標簽,然后將此標簽傳遞給您對選定單元格的特定按鈕執行操作的功能。
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "cell_identifier", for:
indexPath) as! CellClass
cell.button.tag = indexPath.row
cell.button.addTarget(self, action: #selector(playpause), for: .touchUpInside)
}
@objc func playpause(btn : UIButton){
if btn.currentImage == UIImage(named: "Play") {
btn.setImage(UIImage(named : "Pause"), forState: .Normal)
}
else {
btn.setImage(UIImage(named : "Play"), forState: .Normal)
}
// perform your desired action of the button over here
}
Swift中最先進的技術是回調閉包。 它們易於實現且非常高效。
在數據源模型中添加一個屬性
var isPlaying = false
在Interface Builder中,選擇自定義單元中的按鈕,然后按⌥⌘4轉到Attributes Inspector。 在彈出菜單“ State Config
選擇“ Default
然后從“ Image
彈出窗口中選擇適當的圖像,對“ Selected
狀態執行相同的操作。
在自定義單元格中,為該按鈕添加一個回調屬性以及一個插座和動作(將兩者都連接到該按鈕)。 通過isSelected
屬性設置圖像。
@IBOutlet weak var button : UIButton!
var callback : (()->())?
@IBAction func push(_ sender: UIButton) {
callback?()
}
在cellForRow
的控制器中添加回調, item
是數據源數組的當前項目。 按鈕的狀態保持在isPlaying
cell.button.isSelected = item.isPlaying
cell.callback = {
item.isPlaying = !item.isPlaying
cell.button.isSelected = item.isPlaying
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.