隐藏键盘返回按钮

时间:2018-03-07 06:39:41

标签: ios swift3

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

lastTransaction和remarks textfields有字母数字键盘,我得到返回按钮

请帮我解决该如何删除该返回按钮的问题。

以下是代码。

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

        })
    }

}

谢谢..

3 个答案:

答案 0 :(得分: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
}

答案 1 :(得分:0)

试试这个!

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

答案 2 :(得分:0)

您可以将标签分配给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
}