【问题标题】:Allow One UIButton to be selected in an array and deselect other允许在数组中选择一个 UIButton 并取消选择其他
【发布时间】:2018-09-05 02:24:14
【问题描述】:

应用从 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])
            }

        }

【问题讨论】:

    标签: ios swift uibutton selected selectedvalue


    【解决方案1】:

    对于类似效果的单选按钮,您可以执行以下操作

       //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]()

    【讨论】:

    • 感谢您的回答。我正在使用由 由 Sergey Nikitenko 于 2013 年 3 月 5 日创建的 RadioButton 库。 虽然我使用的是 Swift3,但是这个库是基于 ObjC 的,并且 isSelected 定义如下-(RadioButton*) selectedButton { if([self isSelected]) { return self; } else { for(NSValue* v in _sharedLinks) { RadioButton* rb = [v nonretainedObjectValue]; if([rb isSelected]) { return rb; } } } return nil; }跨度>
    • 我不知道这个库,但我已经更新了我的代码。我在故事板上放置了一些按钮并创建了集合(这些按钮的类为RadioButton)并将它们连接到@IBAction。他们像单选按钮一样工作
    • 感谢您的更新。为了更好地阐述我的查询,我没有使用情节提要来创建 RadioButton。故事板有一个 MainView 并将所有其余部分添加为子视图,主要是 UIView,而按钮是基于 UIButton 的 RadioButtons。我希望这能解释我的问题
    • 是的,我正在通过代码 var frame = CGRect(x: j * (squareSize + spacing), y: j * n * (squareSize + spacing), width: 40, height: 40) var img = RadioButton(frame: frame) as? RadioButton let imgName = productOptionArray[j]["name"].stringValue 创建 RadioButtons
    • @DavidBuik:我有机会查看了图书馆。我已经使用库中的RadioButton 更新了我的答案。它对我有用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    • 2021-06-21
    • 2020-05-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多