【问题标题】:Swift - How to access cells nameSwift - 如何访问单元格名称
【发布时间】:2020-10-03 17:26:26
【问题描述】:
import UIKit

class TableViewControllerOne: UITableViewController {


  let musicArray = ["Old Town Road", "Starboy"]

  var songName = ""


  override func viewDidLoad() {
    super.viewDidLoad()
  }

  override func numberOfSections(in tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
  }

  override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return musicArray.count
  }

  override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath)
    cell.textLabel!.text = musicArray[indexPath.row]
    //here is the problem
    songName = cell.textLabel!.text!
    return cell
  }

  override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    var vc = segue.destination as! ViewControllerOne
    vc.songFinalName = self.songName
    
  }

}

所以我正在做音乐播放器应用程序,但我不知道如何播放当前歌曲。我连续播放所有歌曲(标识符为 MyCell)。当我单击名为例如,Starboy 的单元格时,它应该获取该名称并将数据传递给另一个 VC 并在那里播放它,但它总是只播放原始的最新内容,例如有3 首歌曲:Old Town Road, Starboy, Hello,它只能播放最新的歌曲,所以在这个例子中是 Hello。有人可以帮我吗?谢谢阅读。

【问题讨论】:

  • 显示你的 didSelectRow 方法

标签: swift xcode uitableview


【解决方案1】:

您需要实现 tableview 的委托方法 didSelectRowAt,该方法将在用户点击表格视图的任何行时更新 songName 属性

public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
   songName = musicArray[indexPath.row]
}

此外,从 cellForRowAt: indexPath 方法中删除 songName = cell.textLabel!.text!

【讨论】:

  • 为什么不简单地设置 vc.songFinalName 并呈现视图控制器?
  • 我正在考虑让他对现有代码进行最小的更改。我同意触发 segue 的最佳方法应该是从 didSelect 如果你没有什么大事需要照顾
  • 所以,感谢您的回答!它有点工作,但它播放我想要它播放的音乐,然后一起播放一首随机音乐。我只能停止 ,,random" 音乐。我从 cellForRowAt: indexPath 中删除了 songName = cell.textLabel!.text! 并添加了 override public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { songName = musicArray[indexPath. row] // performSegue(withIdentifier: "dataTransport", sender: self) } 当我添加 performSegue 时...它会播放两首歌曲。没有它它只会播放随机歌曲。你知道问题出在哪里吗?谢谢!
  • 您如何执行到 ViewControllerOne 的转换以及如何将歌曲分配给 ViewControllerOne 的 songFinalName 属性似乎有问题。你能分享你的 performSegue 代码和 ViewControllerOne 代码吗
猜你喜欢
  • 1970-01-01
  • 2014-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-22
相关资源
最近更新 更多