Разрешить выбор одной UIB-кнопки в массиве и отменить выбор других - PullRequest
0 голосов
/ 05 сентября 2018

Приложение загружается из параметров продукта 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])
            }

        }

1 Ответ

0 голосов
/ 05 сентября 2018

Для радио-кнопок, подобных эффекту, вы можете сделать что-то вроде следующего:

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

...