如何在swift中轻击UIButton时从数组中删除对象?

时间:2016-02-24 22:17:07

标签: ios arrays swift parse-platform uibutton

我正在创建一个问答游戏,我希望有一个提示功能按钮。现在我从Parse.com获取测验游戏的数据并将其保存在本地阵列中。每次按下提示按钮,我希望它从数组中消除一个错误的答案,并隐藏相应的按钮到该答案。

  @IBOutlet var Button1: UIButton!
  @IBOutlet var Button2: UIButton!
  @IBOutlet var Button3: UIButton!
  @IBOutlet var Button4: UIButton!

  var question: String!
  var answers: [String]!
  var answer: String!  

答案字符串的形式为“1”,“2”,“3”,“4”对应于它们在答案数组中的位置。任何帮助将不胜感激!

这是我正在使用的示例函数,但它没有隐藏错误的答案按钮,而是隐藏了正确的答案按钮!

 func giveHint(sender: UIButton){ 
if self.answer != "1" { answers.removeAtIndex(1) Button1.alpha = 0 } else if self.answer != "2" { answers.removeAtIndex(2) Button2.alpha = 0 } else if self.answer != "3" { answers.removeAtIndex(3) Button3.alpha = 0 } else if self.answer != "4" { answers.removeAtIndex(4) Button4.alpha = 0 } 
} 

使用D Greg的答案如下。唯一的区别是字符串必须转换为Int。这是由Int(字符串)完成的。

2 个答案:

答案 0 :(得分:1)

您可以将按钮设置为数组并隐藏提示点按钮。此代码假定按钮和答案的顺序相同。

@IBOutlet weak var btn1: UIButton!
@IBOutlet weak var btn2: UIButton!
@IBOutlet weak var btn3: UIButton!
@IBOutlet weak var btn4: UIButton!

var question: String!
var wrongAnswers: [String]!
var answer: String!
var btnsArray = [UIButton]()
var wrongBtnsArray = [UIButton]()



override func viewDidLoad() {
    super.viewDidLoad()

    setUpWrongAnswers(2)

}

//call this one in viewDidLoad
func setUpWrongAnswers(rightAnswer: Int) {
    var answers = ["answer1","answer2","answer3","answer4"]
    btnsArray = [btn1, btn2, btn3, btn4]

    wrongBtnsArray = btnsArray
    wrongBtnsArray.removeAtIndex(rightAnswer)

    answers.removeAtIndex(rightAnswer)
    wrongAnswers = answers
}

//creates random wrong answer choice
func wrongAnswer(wrongAnswerCount: Int) -> Int {
    let wrongAnswer = Int(arc4random_uniform(UInt32(wrongAnswerCount - 1)))
    return wrongAnswer
}

func hideAnAnswer(wrongAnswer: Int) {
    if wrongAnswers.count >= 2 {
        wrongAnswers.removeAtIndex(wrongAnswer)
        wrongBtnsArray[wrongAnswer].hidden = true
    }
}


@IBAction func hintBtnTapped(sender: UIButton) {
    hideAnAnswer(wrongAnswer(wrongAnswers.count))
}

//You'll probably want to reset the buttons on the next question
func unHideBtns() {
    for btn in btnsArray {
        btn.hidden = false
    }
}

这应该让你开始。希望它有所帮助!

(编辑:按原样工作)

答案 1 :(得分:1)

数组索引从0开始 我假设当你说它隐藏正确的答案按钮时答案是" 2",因为通过你的giveHint函数,它将从answers数组中删除索引1,这是&# 34; 2"

更改您的giveHint removeAtIndex即可。

func giveHint(sender: UIButton){ 
    if self.answer != "1" { 
        answers.removeAtIndex(0) 
        Button1.alpha = 0 
    } else if self.answer != "2" { 
        answers.removeAtIndex(1) 
        Button2.alpha = 0 
    } else if self.answer != "3" { 
        answers.removeAtIndex(2) 
        Button3.alpha = 0 
    } else if self.answer != "4" { 
        answers.removeAtIndex(3) 
        Button4.alpha = 0 
    } 
}