【问题标题】:If UIButton is selected, unselect the other UIButton in Swift (Xcode 9)如果 UIButton 被选中,在 Swift (Xcode 9) 中取消选择另一个 UIButton
【发布时间】:2018-03-28 09:25:47
【问题描述】:

我正在开发一个应用程序,它可以让我为 Arduino Uno 中的某些 LED 选择不同的颜色。现在,我有点卡在代码中。

如果选择了一个按钮,即一种颜色,则应取消选择另一个按钮,因为一次只能有一种颜色。请看下面的代码。下面的代码是一个所有按钮都有连接的子类。

import UIKit

class ToggleTheButtons: UIButton {

// Buttons are all off on load.
var isOn = false

override init(frame: CGRect) {

    super.init(frame: frame)
    initButton()

}

required init?(coder aDecoder: NSCoder){

    super.init(coder:aDecoder)
    initButton()

}

func initButton(){
    // Initializes the button.
    layer.borderWidth = 0.0

    addTarget(self, action: #selector(ToggleTheButtons.buttonPressed),    for: .touchUpInside)

}

// What happens when we press the buttons.
@objc func buttonPressed() {

    activateButton(bool: !isOn)

}

// Toggles button on and off.
func activateButton(bool: Bool) {

    isOn = bool

    // Ternary operator. true:false (Boolean is nodig)
    _ = bool ? (layer.borderWidth = 2.0) : (layer.borderWidth = 0.0)
    //        layer.borderColor = (borderColorOfTheButton as! CGColor)


}

}

由于我仍在研究我的技能,您可能会在这里找到一些奇怪的代码。请就您发现的错误给我任何反馈。

我期待着阅读您的回复。

编辑:我已经通过 IBActions 链接了我的 UIButtons,截图如下。

您将在下面找到 licht.swift 的代码。这里的按钮是链接的。

import UIKit

class Licht: UIViewController {

// Link alle knoppen met de code. Check ToggleTheButtons.swift voor de     toggle functies. Misschien een IBAction.
//    @IBOutlet weak var redButton: ToggleTheButtons!

@IBAction func redButton(_ sender: ToggleTheButtons) {
}
@IBAction func orangeButton(_ sender: ToggleTheButtons) {
}

@IBAction func yellowButton(_ sender: ToggleTheButtons) {
}

@IBAction func greenButton(_ sender: ToggleTheButtons) {
}

@IBAction func lightBlueButton(_ sender: ToggleTheButtons) {
}

@IBAction func darkBlueButton(_ sender: ToggleTheButtons) {
}

@IBAction func purpleButton(_ sender: ToggleTheButtons) {
}

@IBAction func pinkButton(_ sender: ToggleTheButtons) {
}

@IBAction func whiteButton(_ sender: ToggleTheButtons) {
}




override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.

    func databaseConnection() {

        // Hier komt de connectie met de database. 

    }

}

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

}

此致,

弗兰克。

【问题讨论】:

  • 如何将此类分配给 UIButton?来自故事板或代码?
  • @JD。我已经在上面添加了答案。
  • 可能你可以使用单选按钮的逻辑。如果我没有错,你需要完全一样的逻辑。如果你想要我实现单选按钮的逻辑。请询问。

标签: ios swift uibutton uikit


【解决方案1】:

根据您的故事板布局设计和您的要求,我为您提供了完全不同的解决方案。

如果您可以使用集合视图管理您的设计(网格 3 x 3),则您只能使用具有单个单元格选择权限的 UICollectionView

UICollectionViewCell 中设置按钮并使用UICollectionViewDelegate 方法处理其选择/取消选择:

collectionView(_:didSelectItemAt:)

告诉代理指定索引路径处的项目已被选中。

optional func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)

collectionView(_:didDeselectItemAt:)

告诉代理指定路径上的项目已取消选择。

optional func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath)


试试这个看看:

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

    @IBOutlet var collection: UICollectionView?

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ButtonCell", for: indexPath) as! ButtonsCell
        cell.button.isSelected = cell.isSelected  // handle button selection 
        // or for your toggle button
        // cell.button.isOn = cell.isSelected
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath) as? ButtonsCell
        cell?.button.isSelected = true  // select button

        // or for your toggle button
        // cell.button.isOn = true
    }

    func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath) as? ButtonsCell
        cell?.button.isSelected = false  // deselect button

        // or for your toggle button
        // cell.button.isOn = false
    }

}

// UICollectionViewCell class with your button
class ButtonsCell: UICollectionViewCell {

    @IBOutlet weak var button: ToggleTheButtons!

}

【讨论】:

    【解决方案2】:

    试试这个

    - Set tag to all UIButton (1 - 9)
    - Set borderWidth to all Buttons
    - Connect all the button to the below mentioned IBAction
    
    @IBAction func didTapButton(_ sender: UIButton) {
        for button in self.view.subviews as [UIView] {
            if button is UIButton {
                 // Do whatever you want
                 button.layer.borderColor = button.tag == sender.tag ? UIColor.blue.cgColor : UIColor.lightGray.cgColor
            }
        }
    }
    

    完成了

    【讨论】:

    • 感谢您的回复。为所有 UIButtons 设置标签是什么意思? @IBAction 是否应该放在子类 .swift 文件中?
    • 您可以通过“button.tag = 1”设置按钮标签值或者在Stroyboard的属性检查器中有一个选项
    • 酷。所以所有的按钮都应该链接到同名的同一个动作?
    • 是的,同样的 IBAction 函数
    • 酷。这行得通!现在开始在按钮单击时更改文本:)
    【解决方案3】:

    只需使用 switch 语句:

    switch sender {
        case firstButton:
            firstButton.isSelected = true
            secondButton.isSelected = false
            thirdButton.isSelected = false
        case secondButton:
            secondButton.isSelected = true
            firstButton.isSelected = false
            thirdButton.isSelected = false
        case thirdButton:
            thirdButton.isSelected = true
            secondButton.isSelected = false
            thirdButton.isSelected = false
        default:
            print("Error")
    }
    

    【讨论】:

      【解决方案4】:

      我会创建一个ToggleTheButtons 的数组:

      @IBOutlet var toggleButtons : [ToggleTheButtons]!
      

      并将所有按钮连接到该集合。
      当一个按钮被按下时,您可以停用该数组中的所有按钮,除了被点击的那个。为此,您甚至可以考虑将@IBActions 的数量减少为1,并将所有按钮连接到相同的方法,然后使用sender 过滤掉您必须激活的一个按钮。

      【讨论】:

      • 为您提供出色的答案。 +1
      • @Krunal 我认为 JD 的答案是最好的(理论上),但由于某种原因他删除了它:/
      • @luk2302 感谢您的回复。所有按钮现在都连接到阵列。 @IBAction 和发件人是什么意思?
      【解决方案5】:

      最简单的方法就是前面提到的那个:

          zeroPctButton.isSelected = false
          tenPctButton.isSelected = false
          twentyPctButton.isSelected = false
          
          sender.isSelected = true
      

      此选项有助于节省代码行数。

      【讨论】:

        【解决方案6】:
         Give same button action to all the buttons  
         @IBAction func allButtonsActionsClicked(_ sender: UIButton) {
            sender.isSelected = !sender.isSelected
            button1.isSelected = false
            button2.isSelected = false
            button3.isSelected = false
            sender.isSelected = true
            }
        

        【讨论】:

          【解决方案7】:

          简单地说,当你想选择一个按钮时,试试这个:

          将所有按钮连接到一个 IBAaction

           @IBAction func allButtons (_ sender: UIButton) {
                  
                  firstButton.isSelected = false
                  secondButton.isSelected = false
                  thirdButton.isSelected = false
                  sender.isSelected = true
          }
          
                  
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-10-31
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-01-11
            相关资源
            最近更新 更多