2016-10-01 4 views
1

Я хочу иметь шесть кнопок в моем проекте и хочу, чтобы они всегда были скрыты, кроме одного. И когда я нажимаю кнопку, которая не скрыта, она должна быть скрыта, а другая кнопка должна случайно отображаться и делать то же самое. Если бы кто-то помог мне!Показывать кнопки случайным образом, нажимая их

+0

Добро пожаловать Переполнение стека! Пожалуйста, просмотрите [как спросить] (http://stackoverflow.com/help/how-to-ask), чтобы улучшить свой вопрос. Отправьте код, который вы попробовали, и полученные вами ошибки. Будьте как можно более конкретными, так как это приведет к лучшим ответам. – David

ответ

4

Создать шесть buttons в раскадровку, добавить тег к ним, а затем создать один Action outlet подключать все кнопки, а затем сделать следующее:

@IBAction func button_clicked(_ sender: AnyObject) { 
    // generate a random number which is not the same as the tag that you 
    repeat{ 
     random = Int(arc4random_uniform(6) + 1) 
    } 
    while random == sender.tag 

    // iterate through all subviews in your view to find all buttons 
    for view in self.view.subviews{ 
     // make sure it´s a button 
     if view.isKind(of: UIButton.self){ 
      // create a button from the view you're iterating to 
      let button = view as! UIButton 
      // if the button tag is equal to the random number you just created we want to show that button 
      if button.tag == random{ 
       button.isHidden = false 
      } 
      // else hide it 
      else{ 
       button.isHidden = true 
      } 
     } 
    } 
} 

Here образец проект, который я создал, что делает это, что вы можете попробовать. Убедитесь, что прочитали комментарии в коде выше и поняли, что происходит.

+0

Спасибо, что работает для меня! Но когда я добавляю еще несколько кнопок в свой проект, они тоже исчезают, нажимая одну из шести кнопок. Как я могу это исправить? –

+0

Я добавил этот код в свой проект, чтобы скрыть каждую кнопку, кроме одной. Это нормально? переопределить функ viewDidAppear (_ анимированный: Bool) { BT6.isHidden = истина BT5.isHidden = верно BT4.isHidden = верно BT3.isHidden = верно BT2.isHidden = истина // Скрытие все, кроме одной кнопки, когда view controller load } –

+0

Вам нужно сделать 2 вещи: 1: перетащить их на действие кнопки из раскадровки на '@IBAction func button_clicked (_ sender: AnyObject)' 2: добавить тег в раскадровку –

0

Я предполагаю, что вы положили свои шесть кнопок на свой раскадровки и связали их с вашим классом. Я сделал это довольно быстро, так что это, вероятно, не самый эффективный способ.

Вы хотели бы свой класс код выглядеть примерно так:

override func viewDidAppear(_ animated: Bool) { 
    BT6.isHidden = true 
    BT5.isHidden = true 
    BT4.isHidden = true 
    BT3.isHidden = true 
    BT2.isHidden = true 
    //Hiding all but one button when the view controller loads 
} 

@IBOutlet weak var BT6: UIButton! 
@IBOutlet weak var BT5: UIButton! 
@IBOutlet weak var BT4: UIButton! 
@IBOutlet weak var BT3: UIButton! 
@IBOutlet weak var BT2: UIButton! 
@IBOutlet weak var BT1: UIButton! 

@IBAction func BT6(_ sender: AnyObject) { 
    //this checks when BT6 is pressed and then hides it 
    BT6.isHidden = true 
    let random = Int(arc4random_uniform(UInt32(4))) 
    if random == 0 { 
     BT5.isHidden = false 
    } else if random == 1 { 
     BT4.isHidden = false 
    } else if random == 2 { 
     BT3.isHidden = false 
    } else if random == 3 { 
     BT2.isHidden = false 
    } else if random == 4 { 
     BT1.isHidden = false 
    } 
    //this part creates a randomiser between 0-4 and depending on which number turns out, it will hide a certain button 
} 
@IBAction func BT5(_ sender: AnyObject) { 
    BT5.isHidden = true 
    let random = Int(arc4random_uniform(UInt32(4))) 
    if random == 0 { 
     BT6.isHidden = false 
    } else if random == 1 { 
     BT4.isHidden = false 
    } else if random == 2 { 
     BT3.isHidden = false 
    } else if random == 3 { 
     BT2.isHidden = false 
    } else if random == 4 { 
     BT1.isHidden = false 
    } 
} 
@IBAction func BT4(_ sender: AnyObject) { 
    BT4.isHidden = true 
    let random = Int(arc4random_uniform(UInt32(4))) 
    if random == 0 { 
     BT5.isHidden = false 
    } else if random == 1 { 
     BT6.isHidden = false 
    } else if random == 2 { 
     BT3.isHidden = false 
    } else if random == 3 { 
     BT2.isHidden = false 
    } else if random == 4 { 
     BT1.isHidden = false 
    } 
} 
@IBAction func BT3(_ sender: AnyObject) { 
    BT3.isHidden = true 
    let random = Int(arc4random_uniform(UInt32(4))) 
    if random == 0 { 
     BT5.isHidden = false 
    } else if random == 1 { 
     BT4.isHidden = false 
    } else if random == 2 { 
     BT6.isHidden = false 
    } else if random == 3 { 
     BT2.isHidden = false 
    } else if random == 4 { 
     BT1.isHidden = false 
    } 
} 
@IBAction func BT2(_ sender: AnyObject) { 
    BT2.isHidden = true 
    let random = Int(arc4random_uniform(UInt32(4))) 
    if random == 0 { 
     BT5.isHidden = false 
    } else if random == 1 { 
     BT4.isHidden = false 
    } else if random == 2 { 
     BT3.isHidden = false 
    } else if random == 3 { 
     BT6.isHidden = false 
    } else if random == 4 { 
     BT1.isHidden = false 
    } 
} 
@IBAction func BT1(_ sender: AnyObject) { 
    BT1.isHidden = true 
    let random = Int(arc4random_uniform(UInt32(4))) 
    if random == 0 { 
     BT5.isHidden = false 
    } else if random == 1 { 
     BT4.isHidden = false 
    } else if random == 2 { 
     BT3.isHidden = false 
    } else if random == 3 { 
     BT2.isHidden = false 
    } else if random == 4 { 
     BT6.isHidden = false 
    } 
} 
+0

Спасибо, что мне очень помогло! –

2

UI (раскадровка) enter image description here

В моем случае кнопка номер метки для шести кнопке каждый назначается от 0 до 5.

enter image description here

// 
// ViewController.swift 
// StackOverflow 
// 
// Created by Seoksoon Jang on 2016. 10. 1.. 
// Copyright © 2016년 Seoksoon Jang. All rights reserved. 
// 

import UIKit 

class ViewController: UIViewController { 

var buttonTagNumberArray : Array<Int>? 
var randomIndex : Int? 

@IBOutlet var button1: UIButton! 
@IBOutlet var button2: UIButton! 
@IBOutlet var button3: UIButton! 
@IBOutlet var button4: UIButton! 
@IBOutlet var button5: UIButton! 
@IBOutlet var button6: UIButton! 

@IBAction func button1Action(_ sender: AnyObject) { 

    randomIndex = Int(arc4random_uniform(UInt32(buttonTagNumberArray!.count))) 

    if (randomIndex! == button1.tag) { 
     button1Action(button1) 
    } else { 

     button1.isHidden = true 

     switch randomIndex! { 
      case button1.tag : 
       print("it should happen : \(button1.tag)") 
       break 
      case button2.tag : 
       button2.isHidden = false; 
       break 
      case button3.tag : 
       button3.isHidden = false; 
       break 
      case button4.tag : 
       button4.isHidden = false; 
       break 
      case button5.tag : 
       button5.isHidden = false; 
       break 
      case button6.tag : 
       button6.isHidden = false; 
       break 
      default: 
       // 
       break; 
      } 

     return ; 
    } 
} 

@IBAction func button2Action(_ sender: AnyObject) { 

    randomIndex = Int(arc4random_uniform(UInt32(buttonTagNumberArray!.count))) 

    if (randomIndex! == button2.tag) { 
     button2Action(button2) 
    } else { 

     button2.isHidden = true; 

     switch randomIndex! { 
      case button1.tag : 
       button1.isHidden = false; 
       break 
      case button2.tag : 
       print("it should happen : \(button2.tag)") 
       break 
      case button3.tag : 
       button3.isHidden = false; 
       break 
      case button4.tag : 
       button4.isHidden = false; 
       break 
      case button5.tag : 
       button5.isHidden = false; 
       break 
      case button6.tag : 
       button6.isHidden = false; 
       break 
      default: 
       // 
       break; 
     } 

     return ; 
    } 

} 

@IBAction func button3Action(_ sender: AnyObject) { 

    randomIndex = Int(arc4random_uniform(UInt32(buttonTagNumberArray!.count))) 

    if (randomIndex! == button3.tag) { 
     button3Action(button3) 
    } else { 

     button3.isHidden = true; 

     switch randomIndex! { 
      case button1.tag : 
       button1.isHidden = false; 
       break 
      case button2.tag : 
       button2.isHidden = false; 
       break 
      case button3.tag : 
       print("it should happen : \(button2.tag)") 
       break 
      case button4.tag : 
       button4.isHidden = false; 
       break 
      case button5.tag : 
       button5.isHidden = false; 
       break 
      case button6.tag : 
       button6.isHidden = false; 
       break 
      default: 
       // 
       break; 
     } 

     return ; 
    } 

} 

@IBAction func button4Action(_ sender: AnyObject) { 

    randomIndex = Int(arc4random_uniform(UInt32(buttonTagNumberArray!.count))) 

    if (randomIndex! == button4.tag) { 
     button4Action(button4) 
    } else { 

     button4.isHidden = true; 

     switch randomIndex! { 
      case button1.tag : 
       button1.isHidden = false; 
       break 
      case button2.tag : 
       button2.isHidden = false; 
       break 
      case button3.tag : 
       button3.isHidden = false; 
       break 
      case button4.tag : 
       print("it should happen : \(button2.tag)") 
       break 
      case button5.tag : 
       button5.isHidden = false; 
       break 
      case button6.tag : 
       button6.isHidden = false; 
       break 
      default: 
       // 
       break; 
      } 

     return ; 
    } 

} 

@IBAction func button5Action(_ sender: AnyObject) { 

    randomIndex = Int(arc4random_uniform(UInt32(buttonTagNumberArray!.count))) 

    if (randomIndex! == button5.tag) { 
     button5Action(button5) 
    } else { 

     button5.isHidden = true; 

     switch randomIndex! { 
      case button1.tag : 
       button1.isHidden = false; 
       break 
      case button2.tag : 

       break 
      case button3.tag : 
       button3.isHidden = false; 
       break 
      case button4.tag : 
       button4.isHidden = false; 
       break 
      case button5.tag : 
       print("it should happen : \(button2.tag)") 
       break 
      case button6.tag : 
       button6.isHidden = false; 
       break 
      default: 
       // 
       break; 
     } 

     return ; 
    } 

} 

@IBAction func button6Action(_ sender: AnyObject) { 

    randomIndex = Int(arc4random_uniform(UInt32(buttonTagNumberArray!.count))) 

    if (randomIndex! == button6.tag) { 
     button6Action(button6) 
    } else { 

     button6.isHidden = true; 

     switch randomIndex! { 
      case button1.tag : 
       button1.isHidden = false; 
       break 
      case button2.tag : 
       button2.isHidden = false; 
       break 
      case button3.tag : 
       button3.isHidden = false; 
       break 
      case button4.tag : 
       button4.isHidden = false; 
       break 
      case button5.tag : 
       button5.isHidden = false; 
       break 
      case button6.tag : 
       print("it should happen : \(button2.tag)") 
       break 
      default: 
       // 
       break; 
     } 

     return ; 
    } 

} 

override func viewDidLoad() { 
    super.viewDidLoad() 

    // Do any additional setup after loading the view. 
    buttonTagNumberArray = [button1.tag, button2.tag, button3.tag, button4.tag, button5.tag, button6.tag] 
} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 
} // class end 
+0

все, что я просто хотел использовать, это рекурсия. :п – boraseoksoon