Difference between NSRange and NSMakeRange

The only difference between them is that NSRange(location: 0, length: 5) is an initializer for NSRange while NSMakeRange(0, 5) is a function which creates a new NSRange instance (by using the same initializer inside most likely) and actually is redundant in Swift. Swift has simply inherited it from Objective-C. I would stick to the former

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

Make part of a UILabel bold in Swift

You will want to use attributedString which allows you to style parts of a string etc. This can be done like this by having two styles, one normal, one bold, and then attaching them together: let boldText = “Filter:” let attrs = [NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 15)] let attributedString = NSMutableAttributedString(string:boldText, attributes:attrs) let normalText = “Hi … 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

tech