gpt4 book ai didi

ios - 如何将长按手势识别器添加到 tableview 单元格内的按钮?

转载 作者:搜寻专家 更新时间:2023-11-01 06:17:42 24 4
gpt4 key购买 nike

我正在尝试将长按手势识别器添加到 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()

}

}

关于ios - 如何将长按手势识别器添加到 tableview 单元格内的按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40786780/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com