如何随机分配来自模型阵列的卡片数据而无需重复

时间:2019-07-16 17:48:12

标签: swift xcode view swipe

我正在显示模型数组中的卡数据,每次启动应用程序时如何随机化卡数据,并且不应重复。我正在使用ZLSwipeable视图库通过滑动功能创建卡。这是我编写了所有刷卡代码的函数,在代码中worddata是我已声明的模型数组,例如var wordsdata = ModelRsult。 CardView是我将卡片显示到的视图

screenshot of my card display screen

图像中显示的是香蕉作为第一个数据,现在当我再次运行该应用程序时,它应该首先显示另一个数据,依此类推

我的源代码:

func nextCardView() -> UIView?
    {
        let arrayData = wordsData
        if (self.colorIndex >= arrayData.count)
        {
            return nil
        }

        let cardView = CardView(frame: swipeableView.bounds)

        if loadCardsFromXib
        {
            let contentView = Bundle.main.loadNibNamed("CardContentView", owner: self, options: nil)?.first! as! CardView
            contentView.superVC = self
            contentView.translatesAutoresizingMaskIntoConstraints = false
            contentView.backgroundColor = cardView.backgroundColor

            cardView.addSubview(contentView)

            let data = arrayData[(self.colorIndex)] as ModelResult
            contentView.wordModel = data

            let savedValue = UserDefaults.standard.bool(forKey: "isLangChanged")

            tempLangChanged = savedValue

            if tempLangChanged == false
            {
                if let spanishName = data.cardWordEnglish, spanishName.count != 0
                {
                    contentView.wordSpanish.text = spanishName
                    print(spanishName)
                }
            }
            else
            {
                if let dict = data.cardWordImage, dict.count != 0
                {
                    let url = WS_wordIconUrl + dict
                    contentView.wordImage.kf.indicatorType = .activity
                    contentView.wordImage.kf.setImage(with: URL(string: url))
                }

                if let spanishName = data.cardWordSpanish, spanishName.count != 0
                {
                    contentView.wordSpanish.text = spanishName
                    print(spanishName)
                }
            }



            contentView.soundBtn.addTarget(self, action:#selector(self.soundBtn(sender:)), for: .touchUpInside)
            contentView.hideCard.addTarget(self, action:#selector(self.hideCard(sender:)), for: .touchUpInside)

            contentView.soundBtn.tag = self.colorIndex
            contentView.hideCard.tag = self.colorIndex

            cardView.tag = self.colorIndex
            constrain(contentView, cardView) { view1, view2 in
                view1.left == view2.left
                view1.top == view2.top
                view1.width == cardView.bounds.width
                view1.height == cardView.bounds.height
            }
        }
        colorIndex += 1
        return cardView

    }

1 个答案:

答案 0 :(得分:0)

解决此问题的最佳方法是将卡所在的阵列改组后再使用。就您而言,我会在应用程序启动时对其进行洗牌。

array.shuffle()