简体   繁体   中英

How to Randomise button.setTitle in swift?

I'm creating a quiz using arc4random to randomise the questions I receive. I am wondering how I can randomise which answer appears on which button. Below is some code func Randomize(){

    var RandomNumber = arc4random() % 4
    RandomNumber += 1

    switch (RandomNumber) {

    case 1:

        Question.text = "What greeting would you use in the morning"
        Answer1.setTitle("Hello", forState: UIControlState.Normal)
        Answer2.setTitle("Goodbye", forState: UIControlState.Normal)
        Answer3.setTitle("Good Morning", forState: UIControlState.Normal)
        Answer4.setTitle("See you soon", forState: UIControlState.Normal)
        Answer5.setTitle("Ni Hao", forState: UIControlState.Normal)
        Answer6.setTitle("CTA", forState: UIControlState.Normal)
        CorrectAnswer = "1"
        break

EDIT: What I want is all the greetings to appear on any of the buttons, but all 6 are on one of the buttons.

You use KVC to access your button

Then keep an array titles,then get random title every time.

For example

let keysArray = ["answer1","answer2","answer3","answer4"]
func buttonAtIndex(index:Int)->UIButton?{
    let key = keysArray[index] as String
    let button = self.valueForKey(key) as? UIButton
    return button
}
var labels = ["label1","label2","label3","label4"]
func randomLabelWithButton(){
    for(var i = 0;i < 4;i++){
        let button = self.buttonAtIndex(i)
        let maxIndex =  labels.count
        let randomIndex = Int(arc4random()) % maxIndex
        button?.setTitle(labels[randomIndex], forState: UIControlState.Normal)
        labels.removeAtIndex(randomIndex)
    }
}

you could try something like the following:

let Answer1 = UIButton()
let Answer2 = UIButton()
let Answer3 = UIButton()
let Answer4 = UIButton()
let Answer5 = UIButton()
let Answer6 = UIButton()

let buttons = [Answer1, Answer2, Answer3, Answer4, Answer5, Answer6]

var answers = [
    "this is answer 1",
    "this is answer 2",
    "this is answer 3",
    "this is answer 4",
    "this is answer 5",
    "this is answer 6"
]

for button in buttons {
    let index = Int(arc4random_uniform(UInt32(answers.count)))
    button.setTitle(answers[index], forState: .Normal)
    answers.removeAtIndex(index)
}

println("Answer1 title: \(Answer1.titleForState(.Normal))")
println("Answer2 title: \(Answer2.titleForState(.Normal))")
println("Answer3 title: \(Answer3.titleForState(.Normal))")
println("Answer4 title: \(Answer4.titleForState(.Normal))")
println("Answer5 title: \(Answer5.titleForState(.Normal))")
println("Answer6 title: \(Answer6.titleForState(.Normal))")

Let me answer it in a very simple way:-


switch (RandomNumber) {

case 1:

    Question.text = "What greeting would you use in the morning"

   //Logic goes here

    NSMutableArray *arrAnswers=[[NSMutableArray alloc]  
     initWithObjects:@"Hello",@"Goodbye",@"Good Morning",@"See you soon",@"Ni Hao",@"CTA",nil];
     NSMutableArray *buttons = [NSMutableArray arrayWithObjects: Answer1,Answer2,Answer3,Answer4,Answer5,Answer6, nil];
     for (UIButton *btn in buttons) {
           int randomIndex= arc4random() % [arrAnswers count];
           NSString* btnTitle = [arrAnswers objectAtIndex:randomIndex];
           [btn setTitle:btnTitle forState:UIControlStateNormal]; 
           [arrAnswers removeObjectAtIndex:randomIndex];                        
    }
  //End of Logic 
      CorrectAnswer = "1"
            break

Here are already given answers I'm sharing my way!

// Your Questions and Answer array should be like this. It would be easily managable.
// "questionsAnswers" should be global
self.questionsAnswers = [["question": "What greeting would you use in the morning?",
                           "answers": ["Hello", "Goodbye", "Good Morning", "See you soon", "Ni Hao", "CTA"],
                     "correctAnswer": "1"],
                         ["question": "What greeting would you use in the evening?",
                           "answers": ["Hello", "Goodbye", "Good Evening", "See you soon", "Ni Hao", "CTA"],
                     "correctAnswer": "2"]]


// Use this function when you want to show in quesiton
self.showQuestion()

// Definition 
func showQuestion() {

    let index: NSInteger = (NSInteger)(arc4random_uniform(UInt32(self.questionsAnswers.count)))
    println(index)

    let questionInfo: NSDictionary = self.questionsAnswers.objectAtIndex(index) as! NSDictionary

    // Question Label
    let label: UILabel = UILabel(frame: CGRectMake(0.0, 0.0, 0.0, 0.0)) // frame: Give it accordingly
    label.text = questionInfo.objectForKey("question") as? String
    itsSuperView.addSubview(label)

    let answers: NSArray = questionInfo.objectForKey("answers") as! NSArray

    // "correctAnswerIndex" should be global
    self.correctAnswerIndex = (questionInfo.objectForKey("correctAnswer") as! NSString).integerValue

    for var i=0; i<answers.count; i++ {
        let btn: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
        btn.frame = CGRectMake(0.0, 0.0, 0.0, 0.0) // frame: Give it accordingly
        btn.setTitle(answers.objectAtIndex(i) as! String, forState: UIControlState.Normal)
        btn.addTarget(self, action: "answerAction:", forControlEvents: UIControlEvents.TouchUpInside)
        btn.tag = i
        itsSuperView.addSubview(btn)
    }
}

func answerAction(sender: UIButton) {
    let clickedAnswerIndex: Int = sender.tag
    if (clickedAnswerIndex == self.correctAnswerIndex) {
        println("Correct!")
    }else {
        println("Wrong!")
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM