[英]Swift unable to get callback
我在我的一個viewcontroller中添加了一個注釋框,例如
private lazy var toolbarView: KeyboardToolbar = {
guard let keyboardToolbar = Bundle.main.loadNibNamed("KeyboardToolbar", owner: self, options: nil)?.first as? KeyboardToolbar else {
fatalError("Error")
}
return keyboardToolbar
}()
override var inputAccessoryView: KeyboardToolbar? {
return toolbarView
}
現在在鍵盤工具欄的快捷文件中
@IBAction func sendPressed(_ sender: Any) {
//called on click of send button in the comment box
}
我該如何在viewcontroller代碼中編寫一個函數,該函數在注釋框中的sendPressed上執行。
完整的鍵盤工具欄代碼
class KeyboardToolbar: UIView, UITextViewDelegate {
@IBOutlet weak var textView: UITextView!
override func awakeFromNib() {
super.awakeFromNib()
textView.delegate = self
autoresizingMask = .flexibleHeight
textView.isScrollEnabled = false
textView.text = "Comment"
textView.textColor = UIColor.lightGray
textView.becomeFirstResponder()
}
override var intrinsicContentSize: CGSize {
let textSize = textView.sizeThatFits(CGSize(width: textView.bounds.size.width, height: CGFloat.greatestFiniteMagnitude))
return CGSize(width: bounds.width, height: textSize.height)
}
func textViewDidBeginEditing(_ textView: UITextView) {
if textView.textColor == UIColor.lightGray {
textView.text = nil
textView.textColor = UIColor.black
}
}
func textViewDidChange(_ textView: UITextView) {
invalidateIntrinsicContentSize()
}
@IBAction func sendPressed(_ sender: Any) {
}
}
您可以為KeyboardToolBar
創建自定義協議
protocol KeyboardToolBarDelegates: class {
func sendPressed(_ text: String)
}
現在您可以在KeyboardToolBar中創建委托對象
class KeyboardToolbar: UIView, UITextViewDelegate {
@IBOutlet weak var textView: UITextView!
weak var delegate: KeyboardToolBarDelegates?
@IBAction func sendPressed(_ sender: Any) {
delegate?.sendPressed("Pass your text")
}
}
在您的viewcontroller中實現Delegate:
class mainViewController: UIViewController, KeyboardToolBarDelegates {
private lazy var toolbarView: KeyboardToolbar = {
guard let keyboardToolbar = Bundle.main.loadNibNamed("KeyboardToolbar", owner: self, options: nil)?.first as? KeyboardToolbar else {
fatalError("Error")
}
keyboardToolbar.delegate = self
return keyboardToolbar
}()
override var inputAccessoryView: KeyboardToolbar? {
return toolbarView
}
//Add protocol method
func sendPressed(_ text: String) {
//Method will be called when send pressed from the KeyboardToolBar
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.