Looping using NSRange

It kind of sounds like you’re expecting NSRange to be like a Python range object. It’s not; NSRange is simply a struct typedef struct _NSRange { NSUInteger location; NSUInteger length; } NSRange; not an object. Once you’ve created one, you can use its members in a plain old for loop: NSUInteger year; for(year = years.location; … Read more

Create UITextRange from NSRange

You can create a text range with the method textRangeFromPosition:toPosition. This method requires two positions, so you need to compute the positions for the start and the end of your range. That is done with the method positionFromPosition:offset, which returns a position from another position and a character offset. – (CGRect)frameOfTextRange:(NSRange)range inTextView:(UITextView *)textView { UITextPosition … Read more

How shouldChangeCharactersInRange works in Swift?

Swift 4, Swift 5 This method doesn’t use NSString // MARK: – UITextFieldDelegate extension MyViewController: UITextFieldDelegate { func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if let text = textField.text, let textRange = Range(range, in: text) { let updatedText = text.replacingCharacters(in: textRange, with: string) myvalidator(text: updatedText) } return true } … Read more

NSRange from Swift Range?

Swift String ranges and NSString ranges are not “compatible”. For example, an emoji like πŸ˜„ counts as one Swift character, but as two NSString characters (a so-called UTF-16 surrogate pair). Therefore your suggested solution will produce unexpected results if the string contains such characters. Example: let text = “πŸ˜„πŸ˜„πŸ˜„Long paragraph saying!” let textRange = text.startIndex..<text.endIndex … Read more

NSRange to Range

As of Swift 4 (Xcode 9), the Swift standard library provides methods to convert between Swift string ranges (Range<String.Index>) and NSString ranges (NSRange). Example: let str = “aπŸ‘ΏbπŸ‡©πŸ‡ͺc” let r1 = str.range(of: “πŸ‡©πŸ‡ͺ”)! // String range to NSRange: let n1 = NSRange(r1, in: str) print((str as NSString).substring(with: n1)) // πŸ‡©πŸ‡ͺ // NSRange back to String … Read more