Reputation:
This is a simple Xylophone app from a tutorial that i am following. If we press on each button, a new note is played. It works fine. But when i want to swipe from 1 button to another, there is no sound.
Github link for the complete project: https://github.com/jaineelesh/Xylophone
i have tried with the Touch Drag Enter/Exit/Inside/Outside also, but nothing seems to work for me.
Please help.
ViewController.swift file
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)
}
}
And this is how the app looks.
I am a beginner so my knowledge is very limited. I tried to find the solutions but there are none which explains how to solve my problem with swift 4. If there exists some old solution, then i am not able to understand them.
i tried to use the below events but they don't seem to work.
Upvotes: 1
Views: 1155
Reputation: 433
You have connected event Touch Up Inside
thats why pressing works (your notePressed
function). If you want your code to work also with swiping then try connecting Touch Drag Exit
or Touch Drag Enter
events.
On your last screen select that event and drag it onto
@IBAction func notePressed(_ sender: UIButton) {
// selecting the correct note based on the tag
//playSound(tag: sender.tag)
}
Events names are self-describing but here you can also find explanation
//EDIT: Ok, I probably did not understand you at first. I think that your problem is similar to THIS.
The idea:
Make an outlet collection that contains all your buttons.
@IBOutlet var buttons: [UIButton]!
Use touchesMoved
method (example):
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)
}
}
}
Upvotes: 1