Sur*_*gch 8 keyboard ios swift
我做了一个应用程序内的自定义键盘,取代了系统键盘,当我点击内部时弹出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
}
}
Run Code Online (Sandbox Code Playgroud)
键盘布局是从xib文件加载的.
如何将按钮文本放入文本字段?
笔记:
更新
xib包含所有密钥的文件创建一个swift与该文件同名的文件xib,并在文件设置中将其设置为文件所有者xib。
将所有按键按钮连接到文件中的 IBAction 方法swift。(请参阅下面的代码。)
我使用委托模式在自定义键盘视图和主视图控制器之间进行通信。这使得它们能够解耦。可以换入和换出多个不同的自定义键盘,而无需更改主视图控制器中的详细实现代码。
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!)
}
}
Run Code Online (Sandbox Code Playgroud)
主视图控制器
请注意,它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)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2565 次 |
| 最近记录: |