假设我在应用程序中有六个按钮,我只想在点击所有六个按钮时启用第七个按钮。如何在Xcode 9中实现这一目标?
答案 0 :(得分:0)
这可以作为您的起点。
(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
}
}