I am using a toolbar in the inputAccessoryView property of a textView. When the keyboard shows, it displays the toolbar as expected. When the device is rotated I want to rem
Swift 5
I use this:
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { self.view.endEditing(true) return true }
Swift 5
I use this:
view.autocorrectionType = .no
Xcode 11.6 and iOS 13.6
I was trying to add two toolbars when the keyboard appears.
First, I added on viewDidLoad
self.textView.inputAccessoryView = self.addDefaultToolbar()
When the keyboard appeared, then I selected a text
in UItextView and trying to add the second toolbar option
Here's code which is NOT showing a Toolbar
on a selection of text
.
func textViewDidChangeSelection(_ textView: UITextView) {
if let selectedRange = textView.selectedTextRange{
let selectedText = textView.text(in: selectedRange)
if selectedText != nil && selectedText!.count > 0{
print("selectedText - \(selectedText!)")
if self.defaultToolBar != nil{
self.defaultToolBar?.removeFromSuperview()
self.defaultToolBar = nil
}
self.textView.inputAccessoryView = self.addSelectionToolbar()
}
else{
print("not selectedText - \(selectedText!)")
if self.selectionToolBar != nil{
self.selectionToolBar?.removeFromSuperview()
self.selectionToolBar = nil
}
self.textView.inputAccessoryView = self.addDefaultToolbar()
}
}
}
After adding a self.textView.reloadInputViews()
, I was able to see change second toolbar and vice versa.
Working code.
func textViewDidChangeSelection(_ textView: UITextView) {
if let selectedRange = textView.selectedTextRange{
let selectedText = textView.text(in: selectedRange)
if selectedText != nil && selectedText!.count > 0{
print("selectedText - \(selectedText!)")
if self.defaultToolBar != nil{
self.defaultToolBar?.removeFromSuperview()
self.defaultToolBar = nil
}
self.textView.inputAccessoryView = self.addSelectionToolbar()
self.textView.reloadInputViews()
}
else{
print("not selectedText - \(selectedText!)")
if self.selectionToolBar != nil{
self.selectionToolBar?.removeFromSuperview()
self.selectionToolBar = nil
}
self.textView.inputAccessoryView = self.addDefaultToolbar()
self.textView.reloadInputViews()
}
}
}
myTextView.inputAccessoryView = nil;
[myTextView reloadInputViews];
This removes the toolbar from the view and reloads the view. This way you don't need to call resignFirstResponder and becomeFirstResponder. Additionally, this will still keep your cursor placement and content.
mTextView.inputAccessoryView = [[UIView alloc] initWithFrame:CGRectZero];
[mTextView reloadInputViews];
works for me, setting inputAccessoryView
to nil
will not work, I just don't know why.