ios - 允许在数组中选择一个 UIButton 并取消选择其他 UIButton

标签 ios swift uibutton selected selectedvalue

应用程序从 API 产品选项加载,例如电子商务应用程序的颜色和尺寸。现在,我有点陷入代码困境。

如果选择了一个按钮,让我们说出它的颜色,则应取消选择另一个按钮,因为一次只能选择一种颜色。请看一下下面的代码。下面的代码是点击按钮时的目标操作。

func imgSelected(_ sender: RadioButton) {
    guard let currentButton = sender as? UIButton else { return }

    if ((currentButton.isSelected) != nil){
        currentButton.isSelected = true
        var dict = JSON(self.catalogProductViewModel.getOption[(sender.superview?.tag)!]);
        let productOptionArray : JSON = JSON(dict["product_option_value"].arrayObject!)
        imageId[(sender.superview?.tag)!] = productOptionArray[sender.tag]["product_option_value_id"].stringValue
        currentButton.layer.borderWidth = 3.0
        currentButton.layer.borderColor = UIColor.red.cgColor
        print("Button Not Clicked \((sender as? RadioButton)?.tag)")
    } else {
        currentButton.layer.borderWidth = 0
        currentButton.layer.borderColor = UIColor.clear.cgColor
        print("Button Removed \((sender as? RadioButton)?.tag)")
    }
}

但是我可以看到所有选项都是可选的,我在论坛中尝试了所有可能的示例,但没有与我合作过。将产品选项转换到购物车时,我面临的另一个问题是返回选项标题而不是所选值,例如它转换到“颜色”而不是“红色”。

        else if dict["type"].stringValue == "image" {
            if dict["required"].intValue == 1{
                if imageId[i] == ""{
                    isValid = 1;
                    errorMessage = errorMessage+dict["name"].stringValue

                    print("Error Message", errorMessage)
                }else{
                    optionDictionary[dict["product_option_id"].stringValue] = imageId[i] as AnyObject
                    print("Else is Valid 0", optionDictionary[dict["product_option_id"].stringValue] )
                }

            }else{
                optionDictionary[dict["product_option_id"].stringValue] = imageId[i] as AnyObject
                print("Stand Alone", optionDictionary[dict["product_option_id"].stringValue])
            }

        }

最佳答案

对于像效果这样的单选按钮,您可以执行以下操作

   //This is the implementation of my custom button
class RadioButton: UIButton {
   override var isSelected: Bool {
       didSet {
           refresh()
       }
   }

   private func refresh() {
       //Here We will do when button state changed to selected (maybe radion image selected/ unselected)
       if isSelected {
           //do the selection
           layer.borderWidth = 1.0
        layer.borderColor = UIColor.red.cgColor
       } else {
           //clear the selection
           layer.borderWidth = 0.0
        layer.borderColor = UIColor.clear.cgColor
       }
   }
}



class MyViewController: UIViewController {

     @IBOutlet var radioButtons: [RadioButton]!


    //let say when buttons is clicked we get the call to this function'
    @IBAction private func radioButtonTapped(_ sender: RadioButton) {

        //first clear the buttons selected state
        clearAllSelection()

        //now select the one that triggered this function
        sender.isSelected = true
  }

  //clears selected state for all buttons
  private func clearAllSelection() {
      radioButtons.forEach {
         $0.isSelected = false
      }
  }

}

好吧,最后我有时间研究一下 RadioButton 库,我认为您可能忘记对按钮进行分组,以便它们都属于同一组,因此只会从该组中选择一个。我使用库 createButtonMethod 创建了一个小示例。请检查并告诉我这是否是您想要的。

func createButtons() {

    let xpos: CGFloat = 50
    var ypos: CGFloat = 100

    for i in 1...3 {

        //create the button with frame
        let frame = CGRect(x: xpos, y: ypos, width: 60, height: 50) //frame for the button
        let radioButton = RadioButton(frame: frame)
        radioButton.backgroundColor = UIColor.red

        //append that button
        buttonArray.append(radioButton)

        //increase the ypos
        ypos += 65

        //set the tag
        radioButton.tag = i

        //add the target
        radioButton.addTarget(self, action: #selector(radioButtonSelected(_:)), for: .touchUpInside)

        //set the selected and unselected state image of radio button
        radioButton.setImage(#imageLiteral(resourceName: "checked"), for: .selected)
        radioButton.setImage(#imageLiteral(resourceName: "unchecked"), for: .normal)

        //finally add that button to the view
        view.addSubview(radioButton)

    }

    //set the group
    buttonArray.first!.groupButtons = buttonArray

    //set first one slected
    buttonArray.first!.isSelected = true


    debugPrint(buttonArray)
}




@objc func radioButtonSelected(_ sender: RadioButton) {
    debugPrint("TAG : \(sender.tag)")
}

这里buttonArray是变量var buttonArray = [RadioButton]()

关于ios - 允许在数组中选择一个 UIButton 并取消选择其他 UIButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52176219/

相关文章:

iphone - 具有固定大小自定义图像的 UIButton

ios - 获取从当前位置到达某个地方的时间

ios - 如何获取当前可见 View Controller

objective-c - 对按钮xcode视而不见的函数

iphone - 如何在按钮中存储字符串值(不能使用标签。)

ios - 段更改文本的名称

iphone - 在 iOS 中检查互联网连接的最简单方法是什么?

ios - 24 小时制不格式化日期

iOS 推送通知自定义声音重复?

ios - 使用 Swift 使用 Segue 发送数据