How to add % Key in decimal Keypad

Hi,

I used below code for UITextField Keyboard Type.

sampleTextField.keyboardType = .decimalPad


In the keyborad displayed,how to add % key ?


Thanks

Replies

It is the same question as adding a Done key in keyboard.

I largely copy here code I wrote for this


To do it in a VC.


Declare at the class level:


    let pcButton = UIButton(type: UIButton.ButtonType.custom)


In viewDidLoad:


            pcButton.setTitle("%", for: UIControl.State())
            pcButton.addTarget(self, action: #selector(pcTyped(_:)), for: UIControl.Event.touchUpInside)
            pcButton.isHidden = true


in keyboardWillShow

    @objc func keyboardWillShow(_ note : Notification) -> Void {

                self.pcButton.isHidden = true

                DispatchQueue.main.async { () -> Void in
                    let keyBoardWindow = UIApplication.shared.windows.last  // C'est la fenêtre complete
                    let hauteurWindow = (keyBoardWindow?.frame.size.height ?? 500) - bottomPadding - topPadding
                    var largeurClavier = kBSize.width
                    var xPosPCKey = CGFloat(10)
                    if kBSize.width > 800 {
                        largeurClavier = 3 * kBSize.width / 5
                        xPosPCKey = (kBSize.width - largeurClavier) / 2
                    }
                    let hauteurClavier = kBSize.height - bottomPadding 
                    let offsetVertical : CGFloat = bottomPadding > 0 ? -8 : -16
                    let quartHauteurClavier = hauteurClavier / 4
                    self.pcButton.frame = CGRect(x: xPosReturnKey, y: hauteurWindow - quartHauteurClavier - offsetVertical, width: largeurClavier / 3, height: quartHauteurClavier) // move up a little
                 
                    keyBoardWindow?.addSubview(self.pcButton)
                    usleep(300000)  // Give 0.3s for button to appear

                    UIView.animate(withDuration: (((note.userInfo! as NSDictionary).object(forKey: UIResponder.keyboardAnimationCurveUserInfoKey) as AnyObject).doubleValue)!, delay: 0, options: UIView.AnimationOptions.curveEaseIn, animations: { () -> Void in
                        self.view.frame = self.view.frame.offsetBy(dx: 0, dy: 0)
                    }, completion: { (complete) -> Void in
                        self.pcButton.isHidden = false
                        keyBoardWindow?.bringSubviewToFront(self.pcButton)
                    } )
     }
}

For the final implementation, you may not want to hard-code the usage of the ASCII '%' symbol and instead use a localized value. Not all languages use that specific symbol for percent.

Did this provide you the solution ? If not, where's the problem ?