如何使用应用内自定义键盘的按钮输入文本

How to input text using the buttons of an in-app custom keyboard

我制作了一个应用内自定义键盘,它取代了系统键盘,并在我点击 UITextField 内部时弹出。

这是我的代码:

class ViewController: UIViewController {
    
    var myCustomKeyboard: UIView!
    @IBOutlet weak var textField: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let keyboardNib = UINib(nibName: "Keyboard", bundle: nil)
        myCustomKeyboard = keyboardNib.instantiateWithOwner(self, options: nil)[0] as! UIView
        
        textField.inputView = myCustomKeyboard
    }

}

键盘布局是从 xib 文件加载的。

问题

如何将按钮文本放入文本字​​段?

备注:

更新

我想象的是这样的:

处理按钮事件的新函数

func updateTextfield(sender: UIButton) {
    textField.text = (textField.text ?? "") + (sender.titleForState(.Normal) ?? "")
}

初始化自定义键盘后,注册按钮:

myCustomKeyboard.subviews
    .filter { [=11=] as? UIButton != nil } // Keep the buttons only
    .forEach { ([=11=] as! UIButton).addTarget(self, action: "updateTextfield", forControlEvents: .TouchUpInside)}

设置

  • 创建一个包含所有密钥的 xib 文件
  • 使用自动布局,这样无论稍后将键盘设置为多大,按键都会调整到正确的比例。
  • 创建一个与xib文件同名的swift文件,并在xib文件设置中将其设置为文件所有者。

  • 将所有按键连接到 swift 文件中的 IBAction 方法。 (请参阅下面的代码。)

代码

我正在使用 delegate pattern 在自定义键盘视图和主视图控制器之间进行通信。这允许它们解耦。无需更改主视图控制器中的详细实现代码,即可换入和换出多个不同的自定义键盘。

Keyboard.swift 文件

import UIKit

protocol KeyboardDelegate {
    func keyWasTapped(character: String)
}

class Keyboard: UIView {

    var delegate: KeyboardDelegate?

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        initializeSubviews()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        initializeSubviews()
    }

    func initializeSubviews() {
        let xibFileName = "Keyboard" // xib extention not needed
        let view = NSBundle.mainBundle().loadNibNamed(xibFileName, owner: self, options: nil)[0] as! UIView
        self.addSubview(view)
        view.frame = self.bounds
    }

    @IBAction func keyTapped(sender: UIButton) {
        self.delegate?.keyWasTapped(sender.titleLabel!.text!)
    }

}

主视图控制器

请注意,ViewController 符合我们创建的 KeyboardDelegate 协议。此外,在创建键盘视图实例时,需要设置 heightwidth 则不需要。显然设置文本字段的 inputView 会将键盘视图宽度更新为屏幕宽度,这很方便。

class ViewController: UIViewController, KeyboardDelegate {

    @IBOutlet weak var textField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        // get an instance of the Keyboard (only the height is important)
        let keyboardView = Keyboard(frame: CGRect(x: 0, y: 0, width: 0, height: 300))

        // use the delegate to communicate
        keyboardView.delegate = self

        // replace the system keyboard with the custom keyboard
        textField.inputView = keyboardView
    }

    // required method for keyboard delegate protocol
    func keyWasTapped(character: String) {
        textField.insertText(character)
    }

}

来源

  • 中的建议很有帮助。
  • This answer from Creating a reusable UIView with xib (and loading from storyboard)

相关