隐藏键盘返回按钮

Posted

技术标签:

【中文标题】隐藏键盘返回按钮【英文标题】:Hide a keyboard return button 【发布时间】:2018-03-07 06:39:41 【问题描述】:

我在这个 ViewController 中有多个文本字段,其中对于某些文本字段,我需要带有返回按钮的数字键盘和两个带有字母数字键盘的文本字段和一个带有日期选择器的文本字段。 一切正常,但是当我单击带有字母数字键盘的文本字段时,数字键盘的返回按钮也会出现。

lastTransaction 和备注文本字段有字母数字键盘,我可以在其中获得返回按钮

请帮助我如何删除返回按钮。

下面是代码。

import UIKit

class ATMDiscrepancyViewController: UIViewController, UIScrollViewDelegate,UITextFieldDelegate

var datePicker : UIDatePicker!

@IBOutlet weak var Shortage50: UITextField!
@IBOutlet weak var shortage100: UITextField!
@IBOutlet weak var shortage500: UITextField!
@IBOutlet weak var shortage2000: UITextField!
@IBOutlet weak var overage50: UITextField!
@IBOutlet weak var overage100: UITextField!
@IBOutlet weak var overage500: UITextField!
@IBOutlet weak var overage2000: UITextField!
@IBOutlet weak var soild50: UITextField!
@IBOutlet weak var soild100: UITextField!
@IBOutlet weak var soild2000: UITextField!
@IBOutlet weak var newbd50: UITextField!
@IBOutlet weak var newbd100: UITextField!
@IBOutlet weak var newbd500: UITextField!
@IBOutlet weak var newbd2000: UITextField!
@IBOutlet weak var closingbd50: UITextField!
@IBOutlet weak var closingbd2000: UITextField!
@IBOutlet weak var oldbd50: UITextField!
@IBOutlet weak var oldbd100: UITextField!
@IBOutlet weak var oldbd500: UITextField!
@IBOutlet weak var wrongfeed500: UITextField!
@IBOutlet weak var wrongfeed50: UITextField!
@IBOutlet weak var wrongfeed2000: UITextField!
@IBOutlet weak var preclosing50: UITextField!
@IBOutlet weak var preclosing500: UITextField!
@IBOutlet weak var preclosing2000: UITextField!

@IBOutlet weak var remarks: UITextField!
@IBOutlet weak var lastTransaction: UITextField!
@IBOutlet weak var eodDateTime: UITextField!
@IBOutlet weak var preclosing100: UITextField!
@IBOutlet weak var wrongfeed100: UITextField!
@IBOutlet weak var oldbd2000: UITextField!
@IBOutlet weak var closingbd500: UITextField!
@IBOutlet weak var closingbd100: UITextField!
@IBOutlet weak var soild500: UITextField!
var atmData : SelectedATM! 
@IBOutlet weak var scrollView: UIScrollView!
var activeField: UITextField?
var ATMTransBefore : ATMTransactionEODS1Model? = nil
var ATMTransAfter : ATMTransactionEODS1Model? = nil
var ATMCounterBefore : ATMCounterModel? = nil
var ATMCounterAfter : ATMCounterModel? = nil
var ATMPhysical : PhysicalModel? = nil
var ATMMAster : ATMMasterModel? = nil
var selectedDate : String = ""
var alertControllerScanCode:CustViewController!
let button = UIButton(type: UIButtonType.custom)

@IBOutlet weak var saveAction: UIButton!

func datePickerValuechanged (sender : UIDatePicker)

    let dateFormatter = DateFormatter()
    dateFormatter.dateStyle = DateFormatter.Style.medium
    dateFormatter.timeStyle = DateFormatter.Style.none
    eodDateTime.text = dateFormatter.string(from: sender.date)
    selectedDate = dateFormatter.string(from: sender.date)
    self.view.endEditing(true)



@IBAction func eodAction(_ sender: UITextField) 
    deregisterFromKeyboardNotifications()
    self.button.isHidden=true
    self.pickUpDate(eodDateTime)

func pickUpDate(_ textField : UITextField)
    deregisterFromKeyboardNotifications()
    self.button.isHidden=true
    self.button.isEnabled = false
     NotificationCenter.default.addObserver(self, selector: #selector(ATMDiscrepancyViewController.keyboardRemoveReturn(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    // DatePicker
    self.datePicker = UIDatePicker(frame:CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 216))
    self.datePicker.backgroundColor = UIColor.white
    self.datePicker.datePickerMode = UIDatePickerMode.dateAndTime
    textField.inputView = self.datePicker

    // ToolBar
    let toolBar = UIToolbar()
    toolBar.barStyle = .default
    toolBar.isTranslucent = true
    toolBar.tintColor = UIColor(red: 92/255, green: 216/255, blue: 255/255, alpha: 1)
    toolBar.sizeToFit()

    // Adding Button ToolBar
    let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(ATMDiscrepancyViewController.doneClick))
    let spaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
    let cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(ATMDiscrepancyViewController.cancelClick))
    toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
    toolBar.isUserInteractionEnabled = true
    textField.inputAccessoryView = toolBar




func doneClick() 
    let dateFormatter1 = DateFormatter()
   // let timeFormatter = DateFormatter()
    dateFormatter1.dateStyle = .medium
    dateFormatter1.timeStyle = .none
    dateFormatter1.dateFormat = "yyyy-MM-dd HH:mm:SS"
    eodDateTime.text = dateFormatter1.string(from: datePicker.date)

    eodDateTime.resignFirstResponder()

func cancelClick() 
    eodDateTime.resignFirstResponder()


func handleDatePicker(sender: UIDatePicker) 
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd"
    eodDateTime.text = dateFormatter.string(from: sender.date)
    selectedDate = dateFormatter.string(from: sender.date)  


func doneButton(sender:UIButton)

    eodDateTime.resignFirstResponder() // To resign the inputView on clicking done.
    eodDateTime.text = selectedDate



override func viewDidLoad() 
    super.viewDidLoad()
    self.navigationItem.title = "Discrepancy"

    registerForKeyboardNotifications()

    button.setTitle("Return", for: UIControlState())
    button.setTitleColor(UIColor.black, for: UIControlState())
    button.frame = CGRect(x: 0, y: 163, width: 106, height: 53)
    button.adjustsImageWhenHighlighted = false
    button.addTarget(self, action: #selector(ATMDiscrepancyViewController.Done(_:)), for: UIControlEvents.touchUpInside)


    let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ATMDiscrepancyViewController.dismissKeyboard))
    view.addGestureRecognizer(tap)

    self.Shortage50.delegate = self
    self.shortage100.delegate = self
    self.shortage500.delegate = self
    self.shortage2000.delegate = self
    self.overage50.delegate = self
    self.overage100.delegate = self
    self.overage500.delegate = self
    self.overage2000.delegate = self
    self.soild50.delegate = self
    self.soild100.delegate = self
    self.soild500.delegate = self
    self.soild2000.delegate = self
    self.newbd50.delegate = self
    self.newbd100.delegate = self
    self.newbd500.delegate = self
    self.newbd2000.delegate = self
    self.closingbd50.delegate = self
    self.closingbd100.delegate = self
    self.closingbd500.delegate = self
    self.closingbd2000.delegate = self
    self.oldbd50.delegate = self
    self.oldbd100.delegate = self
    self.oldbd500.delegate = self
    self.oldbd2000.delegate = self
    self.wrongfeed50.delegate = self
    self.wrongfeed100.delegate = self
    self.wrongfeed500.delegate = self
    self.wrongfeed2000.delegate = self
    self.preclosing50.delegate = self
    self.preclosing100.delegate = self
    self.preclosing500.delegate = self
    self.preclosing2000.delegate = self
    self.remarks.delegate = self
    self.lastTransaction.delegate = self
    self.eodDateTime.delegate = self




override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) 
    self.view.endEditing(true)



func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool 

    if textField == self.lastTransaction || textField == self.remarks 

         let textString = (textField.text as! NSString).replacingCharacters(in: range, with: string)

         return true
    
    let allowedCharacters = CharacterSet.decimalDigits
    let characterSet = CharacterSet(charactersIn: string)
    return allowedCharacters.isSuperset(of: characterSet)



func textFieldShouldReturn(_ textField: UITextField) -> Bool 

    self.Shortage50.resignFirstResponder()
    self.shortage100.resignFirstResponder()
    self.shortage500.resignFirstResponder()
    self.shortage2000.resignFirstResponder()

    self.overage50.resignFirstResponder()
    self.overage100.resignFirstResponder()
    self.overage500.resignFirstResponder()
    self.overage2000.resignFirstResponder()

    self.soild50.resignFirstResponder()
    self.soild100.resignFirstResponder()
    self.soild500.resignFirstResponder()
    self.soild2000.resignFirstResponder()

    self.Shortage50.becomeFirstResponder()
    self.lastTransaction.resignFirstResponder()
    self.remarks.resignFirstResponder()

    if textField == self.Shortage50
    
        if isEmptyValidate(edit: self.Shortage50) == true
        
            return false
        
        self.shortage100.becomeFirstResponder()
    
    if textField == self.shortage100
    
        if isEmptyValidate(edit: self.shortage100) == true
        
            return false
        
        self.shortage500.becomeFirstResponder()
    
    if textField == self.shortage500
    
        if isEmptyValidate(edit: self.shortage500) == true
        
            return false
        
        self.shortage2000.becomeFirstResponder()
    
    if textField == self.shortage2000
    
        if isEmptyValidate(edit: self.shortage2000) == true
        
            return false
        
        self.overage50.becomeFirstResponder()
    
    if textField == self.overage50
    
        if isEmptyValidate(edit: self.overage50) == true
        
            return false
        
        self.overage100.becomeFirstResponder()
    
    if textField == self.overage100
    
        if isEmptyValidate(edit: self.overage100) == true
        
            return false
        
        self.overage500.becomeFirstResponder()
    
    if textField == self.overage500
    
        if isEmptyValidate(edit: self.overage500) == true
        
            return false
        
        self.overage2000.becomeFirstResponder()
    
    if textField == self.overage2000
    
        if isEmptyValidate(edit: self.overage2000) == true
        
            return false
        
        self.soild50.becomeFirstResponder()
    
    if textField == self.soild50
    
        if isEmptyValidate(edit: self.soild50) == true
        
            return false
        
        self.soild100.becomeFirstResponder()
    
    if textField == self.soild100
    
        if isEmptyValidate(edit: self.soild100) == true
        
            return false
        
        self.soild500.becomeFirstResponder()
    
    if textField == self.soild500
    
        if isEmptyValidate(edit: self.soild500) == true
        
            return false
        
        self.soild2000.becomeFirstResponder()
    
    if textField == self.soild2000
    
        if isEmptyValidate(edit: self.soild2000) == true
        
            return false
        

        self.button.isHidden=true
         self.lastTransaction.becomeFirstResponder()
        dismissKeyboard()

        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)

    
    if textField == self.lastTransaction
    
        if isEmptyValidate(edit: self.lastTransaction) == true
        
            return false
        
        self.button.isHidden = true
        self.remarks.becomeFirstResponder()
    

    if textField == self.remarks
    
        if isEmptyValidate(edit: self.remarks)
        
            return false
        

    

    return true

  

  func valid() -> Bool
  
      if isEmptyValidate(edit: Shortage50) == true
    
        return false
    
    if isEmptyValidate(edit: shortage100) == true
    
        return false
    
    if isEmptyValidate(edit: shortage500) == true
    
        return false
    
    if isEmptyValidate(edit: shortage2000) == true
    
        return false
    
    if isEmptyValidate(edit: overage50) == true
    
        return false
    
    if isEmptyValidate(edit: overage100) == true
    
        return false
    
    if isEmptyValidate(edit: overage500) == true
    
        return false
    
    if isEmptyValidate(edit: overage2000) == true
    
        return false
    
    if isEmptyValidate(edit: soild50) == true
    
        return false
    
    if isEmptyValidate(edit: soild100) == true
    
        return false
    
    if isEmptyValidate(edit: soild500) == true
    
        return false
    
    if isEmptyValidate(edit: soild2000) == true
    
        return false
    
    if isEmptyValidate(edit: eodDateTime) == true
    
        return false
    
    return true


func isEmptyValidate(edit : UITextField) ->Bool

    if edit.text?.isEmpty ?? true
    
        edit.attributedPlaceholder = NSAttributedString(string: "Enter value", attributes: [NSForegroundColorAttributeName : UIColor.red])
        return true
    
    return false



func registerForKeyboardNotifications()


    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)




func deregisterFromKeyboardNotifications()
    //Removing notifies on keyboard appearing
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)


func keyboardWasShown(notification: NSNotification)
    //Need to calculate keyboard exact size due to Apple suggestions
    self.scrollView.isScrollEnabled = true
    var info = notification.userInfo!
    let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
    let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize!.height, 0.0)

    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets

    var aRect : CGRect = self.view.frame
    aRect.size.height -= keyboardSize!.height
    if let activeField = self.activeField
        if (!aRect.contains(activeField.frame.origin))
            self.scrollView.scrollRectToVisible(activeField.frame, animated: true)
        
    


func keyboardWillBeHidden(notification: NSNotification)
    //Once keyboard disappears, restore original positions
    var info = notification.userInfo!
    self.view.endEditing(true)
    self.scrollView.isScrollEnabled = true


func textFieldDidBeginEditing(_ textField: UITextField)
    activeField = textField

    NotificationCenter.default.addObserver(self, selector: #selector(ATMDiscrepancyViewController.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)




func textFieldDidEndEditing(_ textField: UITextField)
    activeField = nil

func dismissKeyboard() 
    view.endEditing(true)





func keyboardWillShow(_ note : Notification) -> Void
    DispatchQueue.main.async  () -> Void in
        self.button.isHidden = false
        self.scrollView.isScrollEnabled = true
        var info = note.userInfo!
        let keyBoardWindow = UIApplication.shared.windows.last
        self.button.frame = CGRect(x: 0, y: (keyBoardWindow?.frame.size.height)!-53, width: 106, height: 53)
        keyBoardWindow?.addSubview(self.button)
        keyBoardWindow?.bringSubview(toFront: self.button)
        let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
        let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize!.height, 0.0)

        self.scrollView.contentInset = contentInsets
        self.scrollView.scrollIndicatorInsets = contentInsets

        var aRect : CGRect = self.view.frame
        aRect.size.height -= keyboardSize!.height
        if let activeField = self.activeField 
            if (!aRect.contains(activeField.frame.origin))
                self.scrollView.scrollRectToVisible(activeField.frame, animated: true)
            
        


        UIView.animate(withDuration: (((note.userInfo! as NSDictionary).object(forKey: UIKeyboardAnimationCurveUserInfoKey) as AnyObject).doubleValue)!, delay: 0, options: UIViewAnimationOptions.curveEaseIn, animations:  () -> Void in
            self.view.frame = self.view.frame.offsetBy(dx: 0, dy: 0)
        , completion:  (complete) -> Void in

        )



    



func Done(_ sender : UIButton)

    DispatchQueue.main.async  () -> Void in

        self.textFieldShouldReturn(self.activeField!)
    




func keyboardRemoveReturn(_ note : Notification) -> Void
    DispatchQueue.main.async  () -> Void in
        self.button.isHidden = true

        UIView.animate(withDuration: (((note.userInfo! as NSDictionary).object(forKey: UIKeyboardAnimationCurveUserInfoKey) as AnyObject).doubleValue)!, delay: 0, options: UIViewAnimationOptions.curveEaseIn, animations:  () -> Void in
            self.view.frame = self.view.frame.offsetBy(dx: 0, dy: 0)
        , completion:  (complete) -> Void in

        )
    


谢谢..

【问题讨论】:

尝试 lastTransaction.enablesReturnKeyAutomatically = false 禁用返回键 @suhit 我使用了自定义按钮返回.. 所以这不起作用 为什么不能使用 IQKeyboardManager,你不需要在文本字段上添加自定义按钮。 github.com/hackiftekhar/IQKeyboardManager 谁能帮我解决这个问题 【参考方案1】:

请确保已设置文本字段委托。

func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool 

   if textField == self.lastTransaction || textField == remarks 
    self.button.isHidden = true; //button is Return button
    else 
    //show as you required 
   
   return true

【讨论】:

感谢它有效,但仅适用于 lastTransaction 文本字段,不适用于备注和 eoddatetime 文本字段 只需将调试点放在textFieldShouldBeginEditing 并检查何时点击备注文本字段,然后检查 self.button.isHidden 属性。【参考方案2】:

试试这个!

func textFieldDidBeginEditing(textField: UITextField) 
if textField == self.lastTransaction  
    self.button.isHidden = true;

 

【讨论】:

谢谢我现在试过了,但这也不起作用。【参考方案3】:

您可以将标签分配给UIToolbar的cancelButton

let cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(VC.cancelClick))
cancelButton.tag = 1001

然后实现UITextFieldDelegate方法textFieldShouldBeginEditing,您可以在其中检查textField类型并禁用取消/返回按钮

func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool 
     if textField == self.lastTransaction 
        let cancelButton = toolBar.subviews.flatMap ( $0 as? UIBarButtonItem ).filter  $0.tag == 1001 .first as! UIBarButtonItem
        cancelButton.isEnabled = false
     
     return true

【讨论】:

你给cancelButton添加标签了吗?尝试添加断点并检查

以上是关于隐藏键盘返回按钮的主要内容,如果未能解决你的问题,请参考以下文章

如何在不单击后退按钮的情况下隐藏键盘[重复]

appium 隐藏键盘后怎样显示键盘

按下回车键隐藏 android 键盘

按下返回键时隐藏软键盘

当uitextView处于焦点时如何隐藏键盘~~

用右下角的“隐藏按钮”隐藏 iPad 键盘