我正在测试自定义键盘。这就是我需要的:
不确定应用为何崩溃。 PS:并不是所有的键都在代码上。这是我要执行的操作以及两个View Controller的图像。
编辑:错误是:线程1:致命错误:展开一个可选值时意外发现nil
第一个ViewController:
import UIKit
class HomeVC: UIViewController, ButtonTapDelegate {
@IBOutlet var textField1: UITextField!
@IBOutlet var textField2: UITextField!
@IBOutlet var keyboardView: UIView!
var buttonPressed = [String]()
override func viewDidLoad() {
addKeyboard(view: keyboardView)
buttonPressed = [String]()
textField1.inputView = UIView()
textField2.inputView = UIView()
}
func addKeyboard(view: UIView) {
let keyboard = KeyboardVC(nibName: "KeyboardVC", bundle: nil)
view.addSubview(keyboard.view)
addChild(keyboard)
}
func didTapButton(sender: UIButton) {
if sender.tag == 5 {
textField1.text?.append(contentsOf: " ")
} else if sender.tag == 6 {
textField1.text?.removeAll()
buttonPressed = [String]()
} else {
let val = sender.titleLabel?.text
textField1.text?.append(contentsOf: val!)
}
self.textField1.text = buttonPressed.joined(separator: "")
}
}
这是第二个View Controller:
import UIKit
protocol ButtonTapDelegate {
func didTapButton(sender: UIButton)
}
class KeyboardVC: UIViewController {
var delegate: ButtonTapDelegate!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func buttons(_ sender: UIButton) {
delegate.didTapButton(sender: sender)
print(sender)
}
}
答案 0 :(得分:2)
var delegate: ButtonTapDelegate!
从本质上讲,一个隐式展开的可选内容实际上是一个承诺,即您肯定会在尝试访问该变量之前为其赋予一个值。在这种情况下的问题是您还没有这样做。您最有可能希望在第一个视图控制器中执行此操作:
func addKeyboard(view: UIView) {
let keyboard = KeyboardVC(nibName: "KeyboardVC", bundle: nil)
keyboard.delegate = self // Now "delegate" will have a value before the function gets called
view.addSubview(keyboard.view)
addChild(keyboard)
}