ios - 将多个数组相加形成一个最终数组。调试 swift xcode

标签 ios arrays swift xcode debugging

我正在尝试创建一个抽认卡应用程序。我也成功地获得了该应用程序,其中有 11 个不同的抽认卡阵列,所有这些阵列加起来形成一个最终阵列,然后我可以在其中滑动。正如您所看到的,每个组的末尾都有“active: true”。这是因为我有一个设置页面来打开和关闭每个单词组。

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!

struct List {
    let words: [Card] /*Create array of cards*/
    var active: Bool
}



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

let secondList:[Card] = [
    Card(image: UIImage(named: "alligator")!, soundUrl: "alligator"),
    Card(image: UIImage(named: "apple")!, soundUrl: "apple"),
    Card(image: UIImage(named: "grape")!, soundUrl: "grape")
]

override func viewDidLoad() {


    var imageList: [String] {
        let list1 = List(words:firstList, active: true)
        let list2 = List(words:secondList, active: true)

        let wordLists = [list1, list2]

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

            } else {
                return result
            }
        }

        return active

    }

    super.viewDidLoad()

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


    imgPhoto.image = (wordLists)[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.
        }
    }
}
}

error

最佳答案

我认为如果您使用List模型来播放单击的卡片的声音,您可能会遇到问题,最好的方法是使用以下方式修改卡片模型

import Foundation; import UIKit; import AVFoundation

var player: AVAudioPlayer?

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


init(image: UIImage, soundUrl: String, isActive:Bool = true) {
    self.image = image
    self.soundUrl = soundUrl
    self.isActive = isActive 
}
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.prepareToPlay()
        player.play()
    print("play")
    } catch let error {
        print(error.localizedDescription)
    }
}
}

使用 用这个替换你的 viewController 代码

 import UIKit

class SecondViewController: UIViewController , UIGestureRecognizerDelegate  {





var imageIndex: Int = 0
  var itemList:[Card] = []

    func addlist(list:[String], flag:Bool)
    {
       for word in list
        {
         itemList.append(Card(image: UIImage(named: word)!, soundUrl: word,isActive:flag))
       }
    }
    override func viewDidLoad() {
      super.viewDidLoad()
    let list1 = ["lake", "lamb", "lamp", "lark", "leaf", "leash", "left", "leg", "lime", "lion", "lips", "list", "lock", "log", "look", "love", "lunch"]
    let list2 = ["ladder", "ladybug", "laughing", "lawnmower", "lemon", "leopard", "leprechaun", "letters", "licking", "lifesaver", "lifting", "lightbulb", "lightning",
                 "listen", "llama"]
    let list3 = ["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"]
    let list4 = ["apple", "ball", "bell", "bubble", "castle", "fall", "fishbowl", "girl", "owl", "pail", "peel", "pool", "smile", "whale", "wheel"]
    let list5 = ["planet", "plank", "plant", "plate", "play", "plum", "plumber", "plus"]
    let list6 = ["black", "blanket", "blender", "blocks", "blond", "blood", "blow", "blue"]
    let list7 = ["flag", "flipflop", "float", "floor", "flower", "fluffy", "flute", "fly"]
    let list8 = ["glacier", "glad", "glasses", "glide", "glitter", "globe", "glove", "glue"]
    let list9 = ["clam", "clamp", "clap", "claw", "clean", "climb", "clip", "cloud"]
    let list10 = ["sled", "sleep", "sleeves", "slice", "slide", "slime", "slip", "slow"]
    let list11 = ["belt", "cold", "dolphin", "elf", "golf", "melt", "milk", "shelf"]
    addlist(list:list1,flag:true);
    addlist(list:list2,flag:true);
    addlist(list:list3,flag:true);
    addlist(list:list4,flag:true);
    addlist(list:list5,flag:true);
    addlist(list:list6,flag:true);
    addlist(list:list7,flag:true);
    addlist(list:list8,flag:true);
    addlist(list:list9,flag:true);
    addlist(list:list10,flag:true);
    addlist(list:list11,flag:true);

        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)

    }

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

@IBOutlet weak var imgPhoto: UIImageView!


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.
        }
    }
}
}

关于ios - 将多个数组相加形成一个最终数组。调试 swift xcode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45422655/

相关文章:

ios - 如何使用 SDWebImage 从缓存中提取旧的 UIImage 并将其放入占位符?

正在计算事物时的 iOS 事件指示器

javascript - 循环遍历页面中的对象,如果页面包含键,则追加值

javascript - 使用另一个数组的对象属性对数组进行排序

iOS:以编程方式将 UINavigationBar 添加到 UITableView

c++ - 是否可以在另一个模板参数的模板参数中声明模板参数?

ios - 如何使用 Sprite Kit 和 Swift 创建按钮?

swift - 如何在增加或减少倒数计时器时将秒数设置为 00?

swift - CoreData 和 CloudKit Sync 有效,但 NSPersistentStoreRemoteChange 通知永远不会触发

ios - 为什么 Imageview 总是拉伸(stretch) show image stretched iOS?