在 TableView 中显示 UITableViewCell 中的 UIAlertView
Posted
技术标签:
【中文标题】在 TableView 中显示 UITableViewCell 中的 UIAlertView【英文标题】:Show UIAlertView from UITableViewCell in TableView 【发布时间】:2015-08-10 02:15:00 【问题描述】:这里是初学者。很难理解代表以及如何实现它们。
我有一个 TableViewCell 来确定是否存在音频文件。 如果没有音频文件,则在包含 tableViewCell 的 tableView 中显示一个 alertView。有人告诉我,使用代表可以解决这个问题,但不知道如何使用它们。
这是 TableViewCell 的代码,它决定是否显示警报:
class TablePostCellView: UITableViewCell, AVAudioPlayerDelegate
...
@IBAction func playAudio(sender: AnyObject)
//self.post?.audioObject.parsePlaySound()
if self.post?.audioObject.parseSoundPlayBack == nil
println("no audio show alert")
else
println("playAudio")
parseSoundPlayBack.play()
我读到这个:Presenting UIAlertController from UITableViewCell,但它并没有真正帮助我。
【问题讨论】:
【参考方案1】:很多人会告诉您在 UITableView 和 UITableViewCell 之间实现委托/协议模式。它们的意思通常是这样的:
protocol AudioPlayable
func playSoundsIfAble()
class SomeCell: UITableViewCell
var delegate: AudioPlayable?
@IBAction func userDidSomething(sender: AnyObject)
delegate?.playSoundsIfAble()
class SomeTableView: UITableViewController
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
var cell = tableView.dequeReusableCellWithIdentifier("abcd") as SomeCell!
cell.delegate = self
return cell
func playSoundsIfAble()
//Play the sound or show the alert
但与委托协议模式一样普遍,为什么不走在前面,将函数用作 Swift 中的一等公民!
下面是另一种在某些情况下非常有用的方法:
class SomeTableView: UITableViewController, UITableViewDataSource
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
var cell = tableView.dequeueReusableCellWithIdentifier("abcd") as! SomeClass
cell.playSpecificAudioFile =
//Grab a specific audio file that corresponds with this specific cell, and play it
//Since this is being written on the TableView, and not the Cell,
//you probably have access to all the data source stuff you need
//and are much better suited to lining up the indexPath and dataSource here
return cell
private typealias PlaySpecificAudioFile = () -> ()
class SomeClass: UITableViewCell
private var playSpecificAudioFile: PlaySpecificAudioFile?
@IBAction func userDidSomething(sender: AnyObject)
playSpecificAudioFile?()
【讨论】:
以上是关于在 TableView 中显示 UITableViewCell 中的 UIAlertView的主要内容,如果未能解决你的问题,请参考以下文章
为啥图像未显示在目标 C 的 cellforRowAtIndexPath 中