在Swift中删除UIButtons数组

时间:2014-12-17 10:35:46

标签: arrays loops swift uibutton

我正在寻找一种方法来删除在Swift中创建的按钮数组。

我的项目是一个字谜游戏,其中一个单词被分解为字母,随机播放,然后在按钮中显示。这与下面的代码非常吻合。

唯一的问题是我想在显示新单词之前删除按钮,因此它们不会重叠(导致错误的用户界面)。所以我的任务就是:

  1. 检查包含字母的characterArray是否为空,或者是否为

  2. 如果为nil,则加载新单词

  3. 如果已有单词,则在添加新按钮(单词)之前删除按钮(单词)


  4. @IBAction func shuffleString() { 
        txtFileArray = fileContent!.componentsSeparatedByString("\n")
    
        // 1. Shuffle the plist with the words to form anagrams from
        currentQuestion = Int(arc4random_uniform(UInt32(txtFileArray.count)))
        anagramString = txtFileArray.objectAtIndex(currentQuestion) as String
    
        var staticY: CGFloat = self.view.bounds.size.height / 9 * 1; // Static X for all buttons.
        var staticWidth: CGFloat = 46; // Static Width for all Buttons.
        var staticHeight: CGFloat = 46; // Static Height for all buttons.
    
        var staticPadding: CGFloat = 10; // Padding to add between each button.
        var characters: String? = anagramString
    
        // 2. Initialize the buttons for the letters
        var button = UIButton()
    
        // 3. Add the word to the characterArray
        var characterArray = Array(anagramString)
    
        /* HERE I NEED CONDITIONAL STATEMENT AS DESCRIBED IN MY QUESTION: */
        /* CHECK IF CHARACTERARRAY IS EMPTY, IF NOT REMOVE THE CURRENT BUTTONS */
        /* BEFORE ADDING NEW ONES */
        for (index, value) in enumerate(characterArray) {
    
            button.removeFromSuperview() // THE BUTTONS ARE NOT REMOVED
            println("Clear Tiles")
            println("index: \(index) and value: \(value)")
        }
    
        // 4. Add the word from the characterArray to corresponding amount of buttons
        for (index, value) in enumerate(characterArray) /* randomIndex */ {
    
            button = UIButton.buttonWithType(UIButtonType.System) as UIButton
            button = UIButton(frame:CGRectMake(0, 0, 44, 44))
            button.frame.origin.x = (CGFloat(index) * 45.0) + 100.0
            button.setTitleColor(UIColor.blackColor(), forState: .Normal)
            button.setBackgroundImage(UIImage(named:"Tile.png"), forState: .Normal)
            button.setTitle("\(value)", forState: .Normal)
    
            buttonSeriesArray.append(button)
    
            self.view.addSubview(button)
           // println("index: \(index) and value: \(value)")
        }
    
        println(characterArray)
    
    }
    

1 个答案:

答案 0 :(得分:1)

您的代码被破坏了。首先,您创建一个按钮然后将其从superview中删除,但它没有分配给任何按钮。你就是在循环中做到这一点。