【发布时间】:2017-03-07 21:41:38
【问题描述】:
我目前有一个可用的UIToolbar,当我使用UITextField 时,我在键盘上方放置了额外的按钮,但我想在UITextView 上方创建第二个UIToolbar 类型。当我尝试复制我的代码并将其修改为我希望它的外观时,它根本不显示。我不确定我是否做错了什么,或者它是否与我正在使用的 NotificationCenter 和 addObserver 有关。仅供参考,如果需要的话,整个课程称为AddRecipeDirectionVC: UIViewController, UITextViewDelegate。
这是我添加到我的viewDidLoad的观察者代码
override func viewDidLoad() {
super.viewDidLoad()
//...Other Code...
NotificationCenter.default.addObserver(self, selector: #selector(AddRecipeDirectionVC.keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
}
最初,我认为我必须在每个 UIViewController 上添加这个观察者,但我开始认为我正在使用的这段代码可以放在初始 VC 中,它会在其余部分执行项目(目前,我在我添加工具栏的任何 VC 中使用该代码)
接下来,我有 textViewDidBeginEditing 函数,我认为正在添加键盘工具栏。
func textViewDidBeginEditing(_ textView: UITextView) {
if (textView.textColor == UIColor.lightGray) {
textView.text = nil
textView.textColor = UIColor.black
}
self.keyboardToolbar(textView: textView) //Adding Keyboard
}
最后,我有 keyboardWillShow 和 keyboardToolbar 函数
func keyboardWillShow(notification: Notification) {
let keyFrame = ((notification as NSNotification).userInfo![UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
let keyHeight = keyFrame.size.height
self.bottomSpace.constant = keyHeight + 12
}
func keyboardToolbar(textView: UITextView) {
let toolbar: UIToolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: 1, height: 1))
toolbar.barStyle = UIBarStyle.default
toolbar.bounds.size.height = 28
let flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
let done: UIBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "Done Check"), style: UIBarButtonItemStyle.done, target: self, action: #selector(AddRecipeIngredientVC.doneButtonAction))
done.tintColor = UIColor.aqua(alpha: 1.0)
let clear: UIBarButtonItem = UIBarButtonItem(title: "Clear", style: UIBarButtonItemStyle.plain, target: self, action: #selector(AddRecipeDirectionVC.clearButtonAction))
clear.tintColor = UIColor.darkAqua(alpha: 1)
var items = [UIBarButtonItem]()
items.append(clear)
items.append(flexSpace)
items.append(done)
toolbar.items = items
toolbar.sizeToFit()
textView.inputAccessoryView = toolbar }
func doneButtonAction() {
self.directionText.resignFirstResponder()
self.bottomSpace.constant = 12
}
func clearButtonAction() {
directionText.text = ""
}
据我所知,我所做的一切都与其他 VC 中的一样,所以看起来它应该可以工作,但什么都没有出现。如果需要添加任何其他代码,请告诉我。
在此先感谢您为我提供的任何帮助:)
【问题讨论】:
标签: swift3 uitextview uitoolbar uikeyboard xcode8.2