设置下一个按钮和完成按钮,而不是在键盘快速键4中返回

时间:2018-10-30 10:24:55

标签: ios swift xcode10 swift4.2

https://i.stack.imgur.com/yNZh1.gif

当键盘出现在工具栏中时,我需要下一个按钮,上一个按钮和完成按钮 我已经实现了这段代码...

导入UIKit

ViewController类:UIViewController,UITextFieldDelegate {

@IBOutlet weak var textfieldOne: UITextField!
@IBOutlet weak var textFieldTwo: UITextField!
@IBOutlet weak var textFieldThree: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()

}

func setAccessoryViewFor(textField : UITextField)   {
    let toolBar = UIToolbar()
    toolBar.barStyle = .default
    toolBar.isTranslucent = true
    toolBar.sizeToFit()

    // Adds the buttons

    // Add previousButton
    let prevButton = UIBarButtonItem(title: "<", style: .plain, target: self, action: #selector(previousPressed(sender:)))
    prevButton.tag = textField.tag
    if getPreviousResponderFor(tag: textField.tag) == nil {
        prevButton.isEnabled = false
    }

    // Add nextButton
    let nextButton = UIBarButtonItem(title: ">", style: .plain, target: self, action: #selector(nextPressed(sender:)))
    nextButton.tag = textField.tag
    if getNextResponderFor(tag: textField.tag) == nil {
        nextButton.title = "Done"
    }

    let spaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
    toolBar.setItems([prevButton,spaceButton,nextButton], animated: false)
    toolBar.isUserInteractionEnabled = true
    textField.inputAccessoryView = toolBar
}



@objc func nextPressed(sender : UIBarButtonItem) {
    if let nextResponder = getNextResponderFor(tag: sender.tag) {
        nextResponder.becomeFirstResponder()
    } else {
        self.view.endEditing(true)
    }

}

@objc func previousPressed(sender : UIBarButtonItem) {
    if let previousResponder = getPreviousResponderFor(tag : sender.tag)  {
        previousResponder.becomeFirstResponder()
    }
}

func getNextResponderFor(tag : Int) -> UITextField? {
    return self.view.viewWithTag(tag + 1) as? UITextField
}

func getPreviousResponderFor(tag : Int) -> UITextField? {
    return self.view.viewWithTag(tag - 1) as? UITextField
}

}

任何人都可以帮助...

1 个答案:

答案 0 :(得分:0)

您可以注册键盘上的出现/消失事件,并可以通过其顶部的UIToolBarnext按钮添加back。否则,只需集成this库,即可完成几行代码。