'Is there a way to track if the character that user inputed is between two other character in swift?
I'm developing an App, which has this feature: when user press a shortcut button, the UITextView is entered into the corresponding symbol (like "**", "__" or """"). Then the cursor turn back to the position between the pair of symbols, and user input what the want. When user has done, he can press the "enter" button to jump out of the pair of symbol and input sth else. But if the user change the cursor manually, for example he move the cursor out of the symbols.He press enter then display a normal line feed.
I have mostly done this function. But I don't know how to track if the cursor is still between the pair of symbols.
@objc func shortcutFunc(sender: CustomBtn, forEvent: UIEvent) {
insertFromCursor(sender: sender, forEvent: forEvent)
retreat = sender.retreat!
var selectedView: CustomTextView?
if bodyViewUnderEditing {
selectedView = textField.bodyView
} else if titleViewUnderEditing {
selectedView = textField.titleView
}
if let selectedView = selectedView {
let location = selectedView.selectedRange.location
selectedView.selectedRange = NSRange(location: location - sender.retreat!, length: 0)
isShortcutBtnInputing = true
}
}
@objc func insertFromCursor(sender: CustomBtn, forEvent event: UIEvent) {
var selectedView: CustomTextView?
if bodyViewUnderEditing {
selectedView = textField.bodyView
} else if titleViewUnderEditing {
selectedView = textField.titleView
}
if let selectedView = selectedView {
let range = selectedView.selectedRange
let start = selectedView.position(from: selectedView.beginningOfDocument, offset: range.location)!
let end = selectedView.position(from: start, offset: range.length)!
let textRange = selectedView.textRange(from: start, to: end)!
selectedView.replace(textRange, withText: sender.argument!)
}
}
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if textView == textField.bodyView {
if text == "\n", isShortcutBtnInputing, bodyViewUnderEditing {
let location = textField.bodyView.selectedRange.location
textField.bodyView.selectedRange = NSRange(location: location + retreat, length: 0)
isShortcutBtnInputing = false
return false
}
return true
} else if textView == textField.titleView {
if text == "\n" {
if isShortcutBtnInputing, titleViewUnderEditing {
let location = textField.titleView.selectedRange.location
textField.titleView.selectedRange = NSRange(location: location + retreat, length: 0)
isShortcutBtnInputing = false
} else {
textField.bodyView.becomeFirstResponder()
}
return false
}
return true
}
return true
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
