2017-07-28 57 views
1

目前 - 我正在構建flashcard應用程序。該應用程序顯示一個閃存卡陣列,用戶可以左右滑動(下面的代碼)正如您所看到的,有11個不同的圖像陣列(每個陣列包含一組特定的單詞),所有這些陣列加起來最後一個陣列。我有一個音頻文件來連接每個圖像。點擊屏幕上的聲音(聲音文件數組),xcode和swift

問題 - 我想這樣做,當用戶點擊屏幕上的音頻文件將播放。例如,如果湖圖像正在顯示並且用戶點擊屏幕,那麼將會播放該lake.mp4音頻文件,如果用戶也將剩餘的圖像劃過並點擊屏幕,則lamb.mp4音頻文件將播放等。 。我知道我必須添加一個輕敲手勢識別器,但我不知道如何使每個音頻文件都連接正確的圖像。

下面的代碼是我目前正在使用的。

import UIKit 

class SecondViewController: UIViewController , UIGestureRecognizerDelegate { 

@IBAction func home(_ sender: Any) { 
    performSegue(withIdentifier: "home", sender: self) 
} 

@IBOutlet weak var imgPhoto: UIImageView! 

struct List { 
    let words: [String] 
    var active: Bool 
} 

let list1 = List(words:["lake", "lamb", "lamp", "lark", "leaf", "leash", "left", "leg", "lime", "lion", "lips", "list", "lock", "log", "look", "love", "lunch"], active: true) 

let list2 = List(words: ["ladder", "ladybug", "laughing", "lawnmower", "lemon", "leopard", "leprechaun", "letters", "licking", "lifesaver", "lifting", "lightbulb", "lightning", "listen", "llama"], active: true) 

let list3 = List(words: ["alligator", "balance", "ballerina", "balloon", "bowling", "cello", "colors", "curlyhair", "dollar", "dolphin", "elephant", "eyelashes", "gasoline", "goalie", "hula", "jellyfish", "olive", "pillow", "pilot", "polarbear", "rollerskate", "ruler", "silly", "telephone", "television", "tulip", "umbrella", "valentine", "violin", "xylophone", "yellow"], active: true) 

let list4 = List(words: ["apple", "ball", "bell", "bubble", "castle", "fall", "fishbowl", "girl", "owl", "pail", "peel", "pool", "smile", "whale", "wheel"], active: true) 

let list5 = List(words: ["planet", "plank", "plant", "plate", "play", "plum", "plumber", "plus"], active: true) 

let list6 = List(words: ["black", "blanket", "blender", "blocks", "blond", "blood", "blow", "blue"], active: true) 

let list7 = List(words: ["flag", "flipflop", "float", "floor", "flower", "fluffy", "flute", "fly"], active: true) 

let list8 = List(words: ["glacier", "glad", "glasses", "glide", "glitter", "globe", "glove", "glue"], active: true) 

let list9 = List(words: ["clam", "clamp", "clap", "claw", "clean", "climb", "clip", "cloud"], active: true) 

let list10 = List(words:["sled", "sleep", "sleeves", "slice", "slide", "slime", "slip", "slow"], active: true) 

let list11 = List(words: ["belt", "cold", "dolphin", "elf", "golf", "melt", "milk", "shelf"], active: true) 

var imageIndex: Int = 0 

var imageList: [String] { 

    let wordLists = [list1, list2, list3, list4, list5, list6, list7, list8, list9, list10, list11] 



    let active = wordLists.reduce([]) { (result:[String], list:List) in 
     if list.active { 
      return result + list.words 

     } else { 
      return result 
     } 
    } 

    return active 

} 




override func viewDidLoad() { 
    super.viewDidLoad() 

    imgPhoto.image = UIImage(named: imageList[imageIndex]) 

    // Do any additional setup after loading the view. 
    imgPhoto.isUserInteractionEnabled = true 

    let leftSwipe = UISwipeGestureRecognizer(target: self, action: #selector(Swiped(gesture:))) 
    leftSwipe.cancelsTouchesInView = false 

    let rightSwipe = UISwipeGestureRecognizer(target: self, action: #selector(Swiped(gesture:))) 
    rightSwipe.cancelsTouchesInView = false 

    leftSwipe.direction = .left 
    rightSwipe.direction = .right 

    view.addGestureRecognizer(leftSwipe) 
    view.addGestureRecognizer(rightSwipe) 

} 

func Swiped(gesture: UIGestureRecognizer) { 

    if let swipeGesture = gesture as? UISwipeGestureRecognizer { 

     switch swipeGesture.direction { 

     case UISwipeGestureRecognizerDirection.right : 
      print("User swiped right") 

      // decrease index first 

      imageIndex -= 1 

      // check if index is in range 

      if imageIndex < 0 { 

       imageIndex = imageList.count - 1 

      } 

      imgPhoto.image = UIImage(named: imageList[imageIndex]) 

     case UISwipeGestureRecognizerDirection.left: 
      print("User swiped Left") 

      // increase index first 

      imageIndex += 1 

      // check if index is in range 

      if imageIndex > imageList.count - 1 { 

       imageIndex = 0 

      } 

      imgPhoto.image = UIImage(named: imageList[imageIndex]) 

     default: 
      break //stops the code/codes nothing. 
     } 
    } 
} 
} 

import UIKit 

class SecondViewController: UIViewController , UIGestureRecognizerDelegate { 



var imageIndex: Int = 0 
@IBAction func home(_ sender: Any) { 
    performSegue(withIdentifier: "home", sender: self) 
} 

@IBOutlet weak var imgPhoto: UIImageView! 


let itemList:[Card] = [ 
    Card(image: UIImage(named: "alligator")!, soundUrl: "Alligator.m4a"), 
    Card(image: UIImage(named: "apple")!, soundUrl: "Apple.m4a"), 
    Card(image: UIImage(named: "ball")!, soundUrl: "Ball.m4a") 
] 



override func viewDidLoad() { 
    super.viewDidLoad() 


    let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:))) 
    imgPhoto.isUserInteractionEnabled = true 
    imgPhoto.addGestureRecognizer(tapGestureRecognizer) 

    imgPhoto.image = (itemList[0]).image 

    // Do any additional setup after loading the view. 
    imgPhoto.isUserInteractionEnabled = true 

    let leftSwipe = UISwipeGestureRecognizer(target: self, action: #selector(Swiped(gesture:))) 
    leftSwipe.cancelsTouchesInView = false 

    let rightSwipe = UISwipeGestureRecognizer(target: self, action: #selector(Swiped(gesture:))) 
    rightSwipe.cancelsTouchesInView = false 

    leftSwipe.direction = .left 
    rightSwipe.direction = .right 


    view.addGestureRecognizer(leftSwipe) 
    view.addGestureRecognizer(rightSwipe) 

} 

func imageTapped(tapGestureRecognizer: UITapGestureRecognizer) 
{ 

    itemList[imageIndex].playSound() 
    // Your action 
} 

func Swiped(gesture: UIGestureRecognizer) { 

    if let swipeGesture = gesture as? UISwipeGestureRecognizer { 

     switch swipeGesture.direction { 

     case UISwipeGestureRecognizerDirection.right : 
      print("User swiped right") 

      // decrease index first 

      imageIndex -= 1 

      // check if index is in range 

      if imageIndex < 0 { 

       imageIndex = itemList.count - 1 

      } 

      imgPhoto.image = itemList[imageIndex].image 

     case UISwipeGestureRecognizerDirection.left: 
      print("User swiped Left") 
      // increase index first 

      imageIndex += 1 

      // check if index is in range 

      if imageIndex > itemList.count - 1 { 

       imageIndex = 0 

      } 



      imgPhoto.image = itemList[imageIndex].image 
     default: 


      break //stops the code/codes nothing. 
     } 
    } 
} 
} 

import Foundation; import UIKit; import AVFoundation 


class Card: NSObject 
{ 
var image: UIImage 
var soundUrl: String 
var player: AVAudioPlayer? 

init(image: UIImage, soundUrl: String) { 
    self.image = image 
    self.soundUrl = soundUrl 
} 
    func playSound() 
{ 
    guard let url = Bundle.main.url(forResource: self.soundUrl, withExtension: "m4a") else { return } 
    do 
    { 
     try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) 
     try AVAudioSession.sharedInstance().setActive(true) 

     player = try AVAudioPlayer(contentsOf: url) 
     guard let player = player else { return } 
     player.play() 
    print("hhh") 
    } catch let error { 
     print(error.localizedDescription) 
    } 
} 
} 

回答

1

更多格式化結構使用建模與MMVM架構概念

import AVFoundation 

     class Card: NSObject 
     { 
      var image: UIImage 
      var soundUrl: String 
      var player: AVAudioPlayer? 

      init(image: UIImage, soundUrl: String) { 
      self.image = image 
      self.soundUrl = soundUrl 
      } 


     func playSound() 
     { 
      guard let url = Bundle.main.url(forResource: self.soundUrl, withExtension: "mp3") else { return } 
      do 
      { 
       try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) 
       try AVAudioSession.sharedInstance().setActive(true) 

       player = try AVAudioPlayer(contentsOf: url) 
       guard let player = player else { return } 

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

使用

class SecondViewController: UIViewController , UIGestureRecognizerDelegate { 



    var imageIndex: Int = 0 
    @IBAction func home(_ sender: Any) { 
     performSegue(withIdentifier: "home", sender: self) 
    } 

    @IBOutlet weak var imgPhoto: UIImageView! 


    let itemList:[Card] = [ 
     Card(image: UIImage(named: "lake")!, soundUrl: "lake.mp3"), 
     Card(image: UIImage(named: "river")!, soundUrl: "river.mp3"), 
     Card(image: UIImage(named: "ocean")!, soundUrl: "ocean.mp3") 
     ] 



    override func viewDidLoad() { 

super.viewDidLoad() 

let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:))) 
imgPhoto.isUserInteractionEnabled = true 
imgPhoto.addGestureRecognizer(tapGestureRecognizer) 




     imgPhoto.image = (itemList[0] as! Card).image 

     // Do any additional setup after loading the view. 
     imgPhoto.isUserInteractionEnabled = true 

     let leftSwipe = UISwipeGestureRecognizer(target: self, action: #selector(Swiped(gesture:))) 
     leftSwipe.cancelsTouchesInView = false 

     let rightSwipe = UISwipeGestureRecognizer(target: self, action: #selector(Swiped(gesture:))) 
     rightSwipe.cancelsTouchesInView = false 

     leftSwipe.direction = .left 
     rightSwipe.direction = .right 

     view.addGestureRecognizer(leftSwipe) 
     view.addGestureRecognizer(rightSwipe) 

    } 


     func imageTapped(tapGestureRecognizer: UITapGestureRecognizer) 
{ 

itemList[imageIndex].playSound() 
    // Your action 
} 
    func Swiped(gesture: UIGestureRecognizer) { 

     if let swipeGesture = gesture as? UISwipeGestureRecognizer { 

      switch swipeGesture.direction { 

      case UISwipeGestureRecognizerDirection.right : 
       print("User swiped right") 

       // decrease index first 

       imageIndex -= 1 

       // check if index is in range 

       if imageIndex < 0 { 

        imageIndex = imageList.count - 1 

       } 

       imgPhoto.image = itemList[imageIndex].image 

      case UISwipeGestureRecognizerDirection.left: 
       print("User swiped Left") 

       // increase index first 

       imageIndex += 1 

       // check if index is in range 

       if imageIndex > imageList.count - 1 { 

        imageIndex = 0 

       } 

       imgPhoto.image = itemList[imageIndex].image 
      default: 


       break //stops the code/codes nothing. 
      } 
     } 
    } 
} 

你最後的疑慮解決方案

let firstList:[Card] = [ 
     Card(image: UIImage(named: "lake")!, soundUrl: "lake"), 
     Card(image: UIImage(named: "lamb")!, soundUrl: "lamb"), 
     Card(image: UIImage(named: "lamp")!, soundUrl: "lamp") 
      ] 
struct List { 
    let words: [Card] /*Create array of cards*/ 
    var active: Bool 
} 

let list1 = List(words:firstList, active: true) 
let list2 = List(words:secondList, active: true) 

let wordLists = [list1, list2] 

print((wordLists[0] as! List).words[0].soundurl) 

**OUTPUT** 
lake 
+0

我在我的代碼中添加了修訂版,並且出現了一些錯誤。因爲我將每張卡片作爲一個對象,所以不會讓我從他們身上製作一個字符串。我也收到了預期的聲明錯誤。我編輯了這個問題併發布了修改後的代碼和錯誤。 –

+0

好吧,所以我把卡類放在一個單獨的文件中。 Xcode告訴我沒有AVPlayer這樣的模塊。同樣在什麼時候我應該插入單詞[index] .playSound()?我不斷收到錯誤「頂級不允許使用表達式」。另外,我爲我的superviewdidload發現錯誤,說超級不能在類成員之外使用。謝謝 –

+0

謝謝。正如你從我的原始代碼中看到的那樣,這些單詞被分組到了11個不同的列表中,然後每個列表都有一串單詞,並在最後有active = true。這是因爲我有一個設置頁面來打開和關閉每個單詞列表。我怎麼能有11個不同的「itemList」,並有每個列表活動=真?因爲現在它不再是一個字符串,每個列表中都有一串字。 –

0

我建議使用對象數組,而不是使用2個不同的陣列。

例如。創建下面的類:

class Card: NSObject { 
    var image: UIImage 
    var soundUrl: String 

    init(image: UIImage, soundUrl: String) { 
    self.image = image 
    self.soundUrl = soundUrl 
    } 
} 

然後你就可以例如創建卡對象的數組:

let cards = [ 
     Card(image: UIImage(named: "lake"), soundUrl: "lake.mp3"), 
     Card(image: UIImage(named: "river"), soundUrl: "river.mp3"), 
     Card(image: UIImage(named: "ocean"), soundUrl: "ocean.mp3") 
    ] 

然後,當用戶刷卡使用數組cards訪問圖像或聲音URL。數組中的每個元素都是Card,它有2個屬性:UIImage和String(聲音的url)。

PS:模型只是一個例子,它可能是UIImage + URL等。取決於您的需求。

+0

你的答案是正確的,還可以使用MVC架構,但我們仍然可以通過使用MVVm架構來改進答案 –

+0

@JaydeepVyas同意但讓我們誠實。問這個問題的人聽起來很低級。我認爲我們不應該讓答案複雜化。讓它變得簡單。 –

+0

你好,請檢查我關於添加兩個數組的問題。如果你能回答的話,有50個聲望點的獎勵。 –