[英]How to add long press gesture recognizer to a button inside of tableview cell?
我試圖將長按手勢識別器添加到tableview單元格內的按鈕。 但是我不知道我在做什么錯。 我希望我的按鈕在用戶點擊並按住按鈕時播放不同的音頻文件。
我的密碼
import UIKit
import AVFoundation
class ViewController6: UIViewController, UITableViewDataSource, UITableViewDelegate
{
var player = AVQueuePlayer()
@IBOutlet var tableView: UITableView!
override func viewDidLoad()
{
super.viewDidLoad()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
//Functions for tableView
//Cell - For Rifles
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return (arrayOfRifles.count)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell6 = tableView.dequeueReusableCell(withIdentifier: "cell6", for: indexPath) as! ViewControllerTableViewCell6
cell6.myImage.image = UIImage(named: arrayOfRifles[indexPath.row] + ".jpg")
cell6.myButton.setTitle(buttonDataRifles[indexPath.row], for: UIControlState.normal)
cell6.myButton.tag = indexPath.row
cell6.myButton.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
cell6.myButton.addGestureRecognizer(longPressGesture)
return cell6
}
func longPressGesture() {
let lpg = UILongPressGestureRecognizer(target: self, action: "longPress")
lpg.minimumPressDuration = 0.5
}
func longPress(_ sender: UIButton) {
if let url = Bundle.main.url(forResource: soundArrayRiflesUzun[(sender as AnyObject).tag], withExtension: "mp3")
{
player.removeAllItems()
player.insert(AVPlayerItem(url: url), after: nil)
player.play()
}
}
//Action for Sounds
@IBAction func buttonAction(_ sender: UIButton)
{
if let url = Bundle.main.url(forResource: soundArrayRifles[sender.tag], withExtension: "mp3")
{
player.removeAllItems()
player.insert(AVPlayerItem(url: url), after: nil)
player.play()
}
}
}
我在這行中出錯
cell6.myButton.addGestureRecognizer(longPressGesture)
這樣吧
cell6.myButton.addTarget(self, action: #selector(ViewController6.buttonAction(_:)), for: .touchUpInside)
cell6.myButton.addGestureRecognizer(self.longPressGesture())
func longPressGesture() -> UILongPressGestureRecognizer {
let lpg = UILongPressGestureRecognizer(target: self, action: #selector(ViewController6.longPress))
lpg.minimumPressDuration = 0.5
return lpg
}
func longPress(_ sender: UILongPressGestureRecognizer) {
if let url = Bundle.main.url(forResource: soundArrayRiflesUzun[sender.view.tag], withExtension: "mp3")
{
player.removeAllItems()
player.insert(AVPlayerItem(url: url), after: nil)
player.play()
}
}
使您的方法返回lpg
:
func longPressGesture() -> UILongPressGestureRecognizer {
let lpg = UILongPressGestureRecognizer(target: self, action: "longPress")
lpg.minimumPressDuration = 0.5
return lpg
}
並這樣稱呼它:
...
cell6.myButton.addGestureRecognizer(longPressGesture())
return cell6
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.