【问题标题】:How to enable a button only when all the buttons are pressed?如何仅在按下所有按钮时才启用按钮?
【发布时间】:2017-11-22 01:17:17
【问题描述】:

假设我在一个应用中有六个按钮,并且我只想在所有六个按钮都被点击的情况下启用第七个按钮。如何在 Xcode 9 中实现这一点?

【问题讨论】:

  • 您尝试了哪些方法,遇到了哪些问题?
  • @LeoDabus 我。正在创建一个简单的彩票应用程序,我想启用一个按钮,只有在所有插槽都被刮掉后才能将用户带到另一个视图?通过单击按钮将插槽刮掉
  • 所以只需创建一个包含 6 个元素的数组并将所有元素设置为 false。每次用户单击按钮时,将相应的元素更改为 true 并检查您的数组是否包含 false。如果它不只是转到下一个视图控制器
  • @LeoDabus 请给我一个关于如何创建数组并将元素设置为 false 的示例。
  • 您可以将按钮标记为 0 到 5,并将按钮标记用作数组元素的索引。

标签: ios swift button


【解决方案1】:

这可以作为你的起点。

(1)。创建以下数组:

//1. Create An Array To Store The Buttons
var buttonArray = [UIButton]()

//2. Create An Array Of Bools So We Can Determine Which Buttons Have Been Pressed
var buttonCheckArray = [false, false, false, false, false, false]

(2)。生成按钮:

 /// Creates 7 Buttons & Adds Them To The Screen
func createButtons(){

    for index in 0 ..< 7{

        //1. Create The Button
        let button = UIButton(frame: CGRect(x: (index * 100) + index * 10, y: 200 , width: 100, height: 100))
        button.setTitle("\(index)", for: .normal)
        button.backgroundColor = .green
        button.tag = index
        button.addTarget(self, action: #selector(buttonPressed(_:)), for: .touchUpInside)
        print(index)

        //2. Add The Button To The Button Array
        buttonArray.append(button)

        //3. Disable The Final Button
        if button.tag == 6 {
            button.isUserInteractionEnabled = false
        }

        //4. Add The Button To The View
        self.view.addSubview(button)
    }

}

(3)。创建验证函数:

/// Determines Which Button Has Been Pressed & Adjusts The buttonCheckArray
///
/// - Parameter sender: UIButton
@IBAction func buttonPressed(_ sender: UIButton){

    //1. Get The Button Tag
    let buttonPressedIndex = sender.tag

    //2. Change The Background Colour
    sender.backgroundColor = .purple

    //3. Change The Bool Value In The Array For The Six Buttons
    if sender.tag != 6{
        buttonCheckArray[buttonPressedIndex] = true
    }


    if buttonCheckArray.contains(false){
        print("Not All 6 Buttons Have Been Selected")
    }else{
        print("All 6 Buttons Have Been Selected")

        guard let finalButton = buttonArray.last else { return }
        finalButton.isUserInteractionEnabled = true

    }

}

【讨论】:

  • 灌输新手代码会适得其反。 OP 可能会在不理解的情况下复制/粘贴此代码。最好发布解决方案的大纲,让 OP 弄清楚如何将其在线放入代码中。
猜你喜欢
  • 2017-12-27
  • 1970-01-01
  • 2015-01-02
  • 1970-01-01
  • 2019-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-12
相关资源
最近更新 更多