как поменять цвет кнопки и цвет фона в swift - PullRequest
0 голосов
/ 09 апреля 2019

, поэтому я хочу изменить цвет моего текста и границы при нажатии кнопки и изменить его обратно, если не выбран

вот мой код

@objc func button_Select(_ sender: UIButton) {
    let button = sender

    if button.isSelected == true {


        button.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        button.layer.cornerRadius = 10
        button.layer.borderWidth = 1
        button.layer.borderColor = #colorLiteral(red: 0.9424466491, green: 0.6981263757, blue: 0.6917206645, alpha: 1)
        button.titleLabel?.textColor = #colorLiteral(red: 0.9424466491, green: 0.6981263757, blue: 0.6917206645, alpha: 1)
        button.isSelected = false

    } else {


        button.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        button.layer.cornerRadius = 10
        button.layer.borderWidth = 1
        button.layer.borderColor = #colorLiteral(red: 0.6666666667, green: 0.6666666667, blue: 0.6666666667, alpha: 1)
        button.titleLabel?.textColor=#colorLiteral(red: 0.6666666667, green: 0.6666666667, blue: 0.6666666667, alpha: 1)

        button.isSelected = true
    }
}

но результат - когда кнопка выбрана, цвет не меняется на розовый, а когда кнопка не выбрана, фон текста кнопки меняется на серый, а не белый / прозрачный цвет

Ответы [ 4 ]

0 голосов
/ 09 апреля 2019

Используйте следующий код ... это может помочь вам

 @objc func button_Select(_ sender: UIButton) {
    sender.tintColor = UIColor.clear
    if sender.isSelected == true {
        sender.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        sender.layer.cornerRadius = 10
        sender.layer.borderWidth = 1
        sender.layer.borderColor = #colorLiteral(red: 0.9424466491, green: 0.6981263757, blue: 0.6917206645, alpha: 1)
        sender.setTitleColor(#colorLiteral(red: 0.9424466491, green: 0.6981263757, blue: 0.6917206645, alpha: 1), for: .normal)
        sender.isSelected = false

    } else {

        sender.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        sender.layer.cornerRadius = 10
        sender.layer.borderWidth = 1
        sender.layer.borderColor = #colorLiteral(red: 0.6666666667, green: 0.6666666667, blue: 0.6666666667, alpha: 1)
        sender.setTitleColor(#colorLiteral(red: 0.6666666667, green: 0.6666666667, blue: 0.6666666667, alpha: 1), for: .normal)
        sender.isSelected = true
    }
}
0 голосов
/ 09 апреля 2019
Follow this below steps -

1.Choose UITextField from the object library

2.Drag to your storyboard

3.Choose border style as none.

4.Create a Swift file and add this below extension -

extension UIView {

   @IBInspectable var cornerRadius: CGFloat {

    get {

        return layer.cornerRadius

    }

    set {

        layer.cornerRadius = newValue

        layer.masksToBounds = newValue > 0

    }

}

   @IBInspectable var borderWidth: CGFloat {

    get {

        return layer.borderWidth

    }

    set {

        layer.borderWidth = newValue

    }

}

   @IBInspectable var borderColor: UIColor? {

    get {

        return UIColor(cgColor: layer.borderColor!)

    }

    set {

        layer.borderColor = newValue?.cgColor

    }

  }

}



extension UIButton {

  func roundedButton(){

    let maskPAth1 = UIBezierPath(roundedRect: self.bounds,

                                 byRoundingCorners: [.topLeft , .topRight],

                                 cornerRadii:CGSize(width:8.0, height:8.0))

    let maskLayer1 = CAShapeLayer()

    maskLayer1.frame = self.bounds

    maskLayer1.path = maskPAth1.cgPath

    self.layer.mask = maskLayer1

  }

}

extension UITextField {

   func setLeftPaddingPoints(_ amount:CGFloat){

    let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: amount, height: self.frame.size.height))

    self.leftView = paddingView

    self.leftViewMode = .always
}

  func setRightPaddingPoints(_ amount:CGFloat) {
    let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: amount, height: self.frame.size.height))
    self.rightView = paddingView
    self.rightViewMode = .always
  }
}

extension UITextField {

    @IBInspectable var maxLength: Int {
    get {
        if let length = objc_getAssociatedObject(self, &kAssociationKeyMaxLength) as? Int {
            return length
        } else {
            return Int.max
        }
    }
    set {
        objc_setAssociatedObject(self, &kAssociationKeyMaxLength, newValue, .OBJC_ASSOCIATION_RETAIN)
        addTarget(self, action: #selector(checkMaxLength), for: .editingChanged)
    }
}

@objc func checkMaxLength(textField: UITextField) {
    guard let prospectiveText = self.text,
        prospectiveText.count > maxLength
        else {
            return
    }

    let selection = selectedTextRange

    let indexEndOfText = prospectiveText.index(prospectiveText.startIndex, offsetBy: maxLength)
    let substring = prospectiveText[..<indexEndOfText]
    text = String(substring)

    selectedTextRange = selection
   }
}
5.Now you can access this extensions either from storyboard or from code to change the values and see the effects.

6.You can change the corner radius, border width, border colour for UITextField.
Hope this method also helps
0 голосов
/ 09 апреля 2019

используйте значение bool для проверки

// declare var
var checkBool = Bool()

 // In viewDidLoad
 checkBool = true

// On Button Action
@objc func button_Select(_ sender: UIButton) {
   if checkBool == true{
        button.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        button.layer.cornerRadius = 10
        button.layer.borderWidth = 1
        button.layer.borderColor = #colorLiteral(red: 0.9424466491, green: 0.6981263757, blue: 0.6917206645, alpha: 1)
        button.setTitleColor(#colorLiteral(red: 0.9424466491, green: 0.6981263757, blue: 0.6917206645, alpha: 1), for: .normal)
      //  button.setTitleColor(.red, for: .normal)

      checkBool = false
   }else{
        button.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        button.layer.cornerRadius = 10
        button.layer.borderWidth = 1
        button.layer.borderColor = #colorLiteral(red: 0.6666666667, green: 0.6666666667, blue: 0.6666666667, alpha: 1)
        button.titleLabel?.textColor=#colorLiteral(red: 0.6666666667, green: 0.6666666667, blue: 0.6666666667, alpha: 1)

      checkBool = true
   }
}

надеюсь, что это работает для вас

0 голосов
/ 09 апреля 2019

Попробуйте назначить тег кнопке и обновите значение тега как 1 или 0 и примените условие на основе тегов, как будто тег равен 1, затем установите цвет фона

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...