Skip to content

Instantly share code, notes, and snippets.

@ahmattox
Created January 5, 2013 19:35
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahmattox/4463233 to your computer and use it in GitHub Desktop.
Save ahmattox/4463233 to your computer and use it in GitHub Desktop.
UITextField category to handle selections with NSRanges. Adds methods to get an NSRange representing the current selection and to select a range of characters with an NSRange.
//
// UITextField+SelectionRanges.h
// Kitchen Unit Converter
//
// Created by Anthony Mattox on 1/5/13.
// Copyright (c) 2013 Friends of The Web. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UITextField (SelectionRanges)
- (NSRange) selectionRange;
- (void) selectRange:(NSRange) range;
@end
//
// UITextField+SelectionRanges.m
// Kitchen Unit Converter
//
// Created by Anthony Mattox on 1/5/13.
// Copyright (c) 2013 Friends of The Web. All rights reserved.
//
#import "UITextField+SelectionRanges.h"
@implementation UITextField (SelectionRanges)
- (NSRange) selectionRange {
return NSMakeRange([self offsetFromPosition:self.beginningOfDocument toPosition:self.selectedTextRange.start], [self offsetFromPosition:self.selectedTextRange.start toPosition:self.selectedTextRange.end]);
}
- (void) selectRange:(NSRange) range {
UITextPosition *startPosition = [self positionFromPosition:self.beginningOfDocument offset:range.location];
UITextPosition *endPosition = [self positionFromPosition:self.beginningOfDocument offset:range.location+range.length];
self.selectedTextRange = [self textRangeFromPosition:startPosition toPosition:endPosition];
}
@end
@unspokenblabber
Copy link

That's pretty useful. Thanks a lot !

@sheikharshad
Copy link

awesome

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment