ios 使用 InputAccessoryView swift 在键盘顶部添加一个视图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35689528/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 08:37:09  来源:igfitidea点击:

add a view on top of the keyboard using InputAccessoryView swift

iosswiftaccessoryview

提问by user101010

I'm trying to add a uiview to be on top of the keyboard always. I did it first with KeyboardWillShow/Hide, but it dosen't cover all cases and I'm trying to use inputAccesoryView. this is what I tried:

我正在尝试添加一个 uiview 始终位于键盘顶部。我首先使用 KeyboardWillShow/Hide 进行了此操作,但它并未涵盖所有情况,我正在尝试使用 inputAccesoryView。这是我试过的:

private var accessoryView = UIView(frame: CGRectZero)

class ViewController : UIViewController {

var myView: customUIView

override var inputAccessoryView: UIView {
    return accessoryView
}

override func canBecomeFirstResponder() -> Bool {
    return true
}

override func viewDidLoad() {
   super.viewDidLoad()
   accessoryView = myView
}
}

I get the following error :

我收到以下错误:

Terminating app due to uncaught exception 'UIViewControllerHierarchyInconsistency', reason: 'child view controller:UICompatibilityInputViewController should have parent view controller:MyViewController but requested parent is: UIInputWindowController: '

由于未捕获的异常“UIViewControllerHierarchyInconsistency”而终止应用程序,原因:“子视图控制器:UICompatibilityInputViewController 应该具有父视图控制器:MyViewController 但请求的父项是:UIInputWindowController:”

any help will be appreciated!

任何帮助将不胜感激!

回答by paulvs

To get a view to stick above the keyboard, the code itself is pretty simple. The code you posted is not correct, try this (note that you must connect textFieldto the UITextFieldin your storyboard):

为了让视图位于键盘上方,代码本身非常简单。您发布的代码不正确,请尝试此操作(请注意,您必须连接textFieldUITextField故事板中的 ):

@IBOutlet weak var textField: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()

    let customView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 44))
    customView.backgroundColor = UIColor.red
    textField.inputAccessoryView = customView
}

回答by Vasily Bodnarchuk

Details

细节

  • Xcode 11.2 (11B52), Swift 5
  • Xcode 11.2 (11B52),Swift 5

Solution

解决方案

KeyboardToolbarButton

键盘工具栏按钮

import UIKit

enum KeyboardToolbarButton: Int {

    case done = 0
    case cancel
    case back, backDisabled
    case forward, forwardDisabled

    func createButton(target: Any?, action: Selector?) -> UIBarButtonItem {
        var button: UIBarButtonItem!
        switch self {
            case .back: button = .init(title: "back", style: .plain, target: target, action: action)
            case .backDisabled:
                button = .init(title: "back", style: .plain, target: target, action: action)
                button.isEnabled = false
            case .forward: button = .init(title: "forward", style: .plain, target: target, action: action)
            case .forwardDisabled:
                button = .init(title: "forward", style: .plain, target: target, action: action)
                button.isEnabled = false
            case .done: button = .init(title: "done", style: .plain, target: target, action: action)
            case .cancel: button = .init(title: "cancel", style: .plain, target: target, action: action)
        }
        button.tag = rawValue
        return button
    }

    static func detectType(barButton: UIBarButtonItem) -> KeyboardToolbarButton? {
        return KeyboardToolbarButton(rawValue: barButton.tag)
    }
}

KeyboardToolbar

键盘工具栏

import UIKit

protocol KeyboardToolbarDelegate: class {
    func keyboardToolbar(button: UIBarButtonItem, type: KeyboardToolbarButton, isInputAccessoryViewOf textField: UITextField)
}

class KeyboardToolbar: UIToolbar {

    private weak var toolBarDelegate: KeyboardToolbarDelegate?
    private weak var textField: UITextField!

    init(for textField: UITextField, toolBarDelegate: KeyboardToolbarDelegate) {
        super.init(frame: .init(origin: .zero, size: CGSize(width: UIScreen.main.bounds.width, height: 44)))
        barStyle = .default
        isTranslucent = true
        self.textField = textField
        self.toolBarDelegate = toolBarDelegate
        textField.inputAccessoryView = self
    }

    func setup(leftButtons: [KeyboardToolbarButton], rightButtons: [KeyboardToolbarButton]) {
        let leftBarButtons = leftButtons.map {
            
import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        textField.addKeyboardToolBar(leftButtons:  [.back, .forwardDisabled], rightButtons:  [.done], toolBarDelegate: self)
    }
}

extension ViewController: KeyboardToolbarDelegate {
   func keyboardToolbar(button: UIBarButtonItem, type: KeyboardToolbarButton, isInputAccessoryViewOf textField: UITextField) {
        print("Tapped button type: \(type) | \(textField)")
    }
}
.createButton(target: self, action: #selector(buttonTapped)) } let rightBarButtons = rightButtons.map {
import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        createTextField(frame: CGRect(x: 50, y: 50, width: 200, height: 40), leftButtons: [.backDisabled, .forward], rightButtons: [.cancel])
        createTextField(frame: CGRect(x: 50, y: 120, width: 200, height: 40), leftButtons: [.back, .forwardDisabled], rightButtons: [.done])
    }

    private func createTextField(frame: CGRect, leftButtons: [KeyboardToolbarButton] = [], rightButtons: [KeyboardToolbarButton] = []) {
        let textField = UITextField(frame: frame)
        textField.borderStyle = .roundedRect
        view.addSubview(textField)
        textField.addKeyboardToolBar(leftButtons: leftButtons, rightButtons: rightButtons, toolBarDelegate: self)
    }
}

extension ViewController: KeyboardToolbarDelegate {
   func keyboardToolbar(button: UIBarButtonItem, type: KeyboardToolbarButton, isInputAccessoryViewOf textField: UITextField) {
        print("Tapped button type: \(type) | \(textField)")
    }
}
.createButton(target: self, action: #selector(buttonTapped(sender:))) } let spaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) setItems(leftBarButtons + [spaceButton] + rightBarButtons, animated: false) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } @objc func buttonTapped(sender: UIBarButtonItem) { guard let type = KeyboardToolbarButton.detectType(barButton: sender) else { return } toolBarDelegate?.keyboardToolbar(button: sender, type: type, isInputAccessoryViewOf: textField) } } extension UITextField { func addKeyboardToolBar(leftButtons: [KeyboardToolbarButton], rightButtons: [KeyboardToolbarButton], toolBarDelegate: KeyboardToolbarDelegate) { let toolbar = KeyboardToolbar(for: self, toolBarDelegate: toolBarDelegate) toolbar.setup(leftButtons: leftButtons, rightButtons: rightButtons) } }

Usage

用法

override var inputAccessoryView: UIView? {
    get {
       return containerView
    }
}
override var canBecomeFirstResponder: Bool {
   return true
}

Full example of usage

完整的使用示例

##代码##

Xcode 11.2 layout problem

Xcode 11.2 布局问题

Results

结果

enter image description here

在此处输入图片说明



enter image description here

在此处输入图片说明



enter image description here

在此处输入图片说明

回答by Hoang Anh Tuan

Try this.

尝试这个。

##代码##

回答by ma11hew28

Changes to make to your code:

对您的代码进行的更改:

  • Give accessoryViewa height
  • Delete var myView: customUIView& the entire viewDidLoad()override
  • accessoryView个高度
  • 删除var myView: customUIView和整个viewDidLoad()覆盖