这是我的代码:
- 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
- }
- }
题
如何将按钮文本放入文本字段?
笔记:
>有很多关于制作自定义系统键盘的教程(需要安装),但我只想要一个应用内键盘.教程使用一个特殊的视图控制器只为键盘,但在这里似乎我只是设置键盘视图.
>我已阅读Custom Views for Data Input文档.
> This是我能找到的最接近的Stack Overflow问题,但它没有描述如何从按钮获取文本.
更新
> This tutorial似乎表明自定义输入视图有一个视图控制器.但是,我在Objective-C代码中迷失了方向. Swift的过程是什么?
> This answer提到了UITextField符合的UIKeyInput协议,但我该如何使用它?
>如果有任何内置方式也可以制作自定义应用内键盘,我真的更喜欢制作一个普通的自定义视图.
解决方法
>制作包含所有密钥的xib文件
>使用Autolayout,无论键盘设置得多大,按键都会调整到正确的比例.
>创建一个与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协议.此外,在创建键盘视图的实例时,需要设置高度,但宽度不需要.显然,设置文本字段的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)
- }
- }
来源
> @ryancrunchi’s comment的建议很有帮助.
> This answer从Creating a reusable UIView with xib (and loading from storyboard)
有关
> A Swift example of Custom Views for Data Input (custom in-app keyboard)