I am confused regarding the functionality of NSRange.
What is the function of NSRange in this code?
shouldChangeTextIn range: NSRange
I am confused regarding the functionality of NSRange.
What is the function of NSRange in this code?
shouldChangeTextIn range: NSRange
Foundation
is an old pre-Swift framework. It's mostly written in Objective-C and uses its types. NSRange
is a C struct heavily used in Objective-C in conjunction with NSString
.
NSString
is converted to Swift as String
and most methods using NSRange
has been converted to methods using Range
(or other Swift types). However, in some methods the Objective-C type still exists for various compatibility reasons. UITextViewDelegate
and UITextFieldDelegate
are prime examples.
To properly use NSRange
you should convert String
to a NSString
first, e.g.:
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText: String) -> Bool
let previousText = (textView.text ?? "") as NSString
let newText = previousText.replacingCharacters(in: range, with: replacementText)
...
}
In this method the range
describes the range of string that is being changed. Its locations
tells you where the new text is being put and its length
tells you how much of previous text is being replaced/removed.
For example a NSRange(location: 2, length: 1)
with replacementText: ""
tells you that the third character is being removed (e.g. when backspace is pressed).