ios - 当手指从一个按钮拖动到下一个按钮时如何触发 UIButton 事件

标签 ios swift uibutton

这是我正在学习的教程中的一个简单木琴应用程序。 如果我们按下每个按钮,就会播放一个新音符。它工作正常。 但是当我想从一个按钮滑动到另一个按钮时,没有声音。

完整项目的 Github 链接: https://github.com/jaineelesh/Xylophone

我也尝试过 Touch Drag Enter/Exit/Inside/Outside,但似乎对我没有任何作用。

请帮忙。

ViewController.swift 文件

import UIKit
import AVFoundation

class ViewController: UIViewController{

var player: AVAudioPlayer?

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

@IBAction func noteOnDrag(_ sender: UIButton) {
    // selecting the correct note based on the tag
    //playSound(tag: sender.tag)
    print("enter")
}

@IBAction func noteOnDragExit(_ sender: UIButton) {
    print("Exit")
}

@IBAction func notePressed(_ sender: UIButton) {
    // selecting the correct note based on the tag
    //playSound(tag: sender.tag)
}

func playSound(tag: Int) {
    let note = "note" + String(tag)
    guard let url = Bundle.main.url(forResource: note, withExtension: "wav") else { return }

    do {
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
        try AVAudioSession.sharedInstance().setActive(true)

        player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.wav.rawValue)

        guard let player = player else { return }

        player.play()
    } catch let error {
        print(error.localizedDescription)
    }
}

这就是应用程序的外观。 enter image description here

我是初学者,所以我的知识非常有限。我试图找到解决方案,但没有一个可以解释如何使用 swift 4 解决我的问题。如果存在一些旧的解决方案,那么我无法理解它们。 我尝试使用以下事件,但它们似乎不起作用。 enter image description here

最佳答案

您已连接事件 Touch Up Inside 这就是为什么按下有效(您的 notePressed 功能)。如果您希望您的代码也适用于滑动,请尝试连接 Touch Drag ExitTouch Drag Enter 事件。

在最后一个屏幕上选择该事件并将其拖到

@IBAction func notePressed(_ sender: UIButton) {
    // selecting the correct note based on the tag
    //playSound(tag: sender.tag)
}

事件名称是自描述的,但 here你也可以找到解释

//编辑: 好吧,一开始我可能不理解你。 我认为您的问题类似于 THIS .

想法:

  1. 制作一个包含所有按钮的 outlet 集合。

    @IBOutlet var buttons: [UIButton]!
    
  2. 使用touchesMoved方法(示例):

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesMoved(touches, with: event)
        guard let touch = event?.allTouches?.first else {return}
        let touchLocation = touch.location(in: self.view)
        buttons.forEach { (button) in
            if button.frame.contains(touchLocation) {
                print(button.tag)
            }
        }
    }
    

关于ios - 当手指从一个按钮拖动到下一个按钮时如何触发 UIButton 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52144876/

相关文章:

ios - 我如何对 Musik 的开关和按钮进行编程?

ios - 从 UIWebView 中的链接打开 iOS6 Apple Maps 应用程序

ios - 更新到 Mountain Lion 后构建失败

ios swift 应用程序扩展以共享图像

swift - 如何在 Swift 中显示当前运行的类和函数

ios - 如何调整所有屏幕尺寸的 View ?

ios - 将字符串作为标签或按钮中的其他值传递

ios - 单击将带有 UIButton 的 UIView 添加到 UIWindow

ios - UIAlertController Objective-C 的 boolean 值

IOS 9 - subview 上的 UIButton 不触发 IBAction socket