[英]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 { $0 as? UIButton != nil } // Keep the buttons only
.forEach { ($0 as! UIButton).addTarget(self, action: "updateTextfield", forControlEvents: .TouchUpInside)}
xib
文件 創建一個swift
與同名的文件xib
文件,並將其設置為在文件所有者xib
文件設置。
將所有關鍵按鈕連接到swift
文件中的IBAction方法。 (請參見下面的代碼。)
我正在使用委托模式在自定義鍵盤視圖和主視圖控制器之間進行通信。 這允許它們解耦。 可以交換多個不同的自定義鍵盤,而無需在主視圖控制器中更改詳細的實現代碼。
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
協議。 另外,在創建鍵盤視圖的實例時,需要設置height
,但不需要設置width
。 顯然,設置文本字段的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)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.