Skip to content

Instantly share code, notes, and snippets.

@fjolnir
Created June 30, 2015 06:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fjolnir/fdd7735e60ad72a93918 to your computer and use it in GitHub Desktop.
Save fjolnir/fdd7735e60ad72a93918 to your computer and use it in GitHub Desktop.
@import ObjectiveC.runtime;
#import "LETextField.h"
@interface LETextField () <UITextFieldDelegate>
@end
@implementation LETextField {
__weak id<UITextFieldDelegate> _realDelegate;
}
- (void)_init
{
[super setDelegate:self];
}
- (instancetype)initWithFrame:(CGRect const)aFrame
{
if((self = [super initWithFrame:aFrame]))
[self _init];
return self;
}
- (instancetype)initWithCoder:(NSCoder * const)aDecoder
{
if((self = [super initWithCoder:aDecoder]))
[self _init];
return self;
}
- (void)setDelegate:(id<UITextFieldDelegate> const)aDelegate
{
_realDelegate = aDelegate;
}
- (id<UITextFieldDelegate>)delegate
{
return _realDelegate;
}
- (void)forwardInvocation:(NSInvocation *)anInvocation
{
BOOL isDelegateMethod =
protocol_getMethodDescription(@protocol(UITextFieldDelegate), anInvocation.selector, NO, YES).name
|| protocol_getMethodDescription(@protocol(UITextFieldDelegate), anInvocation.selector, YES, YES).name;
if(isDelegateMethod)
anInvocation.target = _realDelegate;
[anInvocation invoke];
}
- (BOOL) textField:(UITextField *)aTextField
shouldChangeCharactersInRange:(NSRange)aRange
replacementString:(NSString *)aReplacementString
{
if(_formatter) {
NSString *newString = [self.text stringByReplacingCharactersInRange:aRange withString:aReplacementString];
NSRange const oldSelection = {
[self offsetFromPosition:self.beginningOfDocument toPosition:self.selectedTextRange.start],
[self offsetFromPosition:self.selectedTextRange.start toPosition:self.selectedTextRange.end]
};
NSRange newSelectionRange = oldSelection;
BOOL const valid = [_formatter isPartialStringValid:&newString
proposedSelectedRange:&newSelectionRange
originalString:self.text
originalSelectedRange:oldSelection
errorDescription:NULL];
if(!valid) {
if(![_realDelegate respondsToSelector:_cmd]
|| [_realDelegate textField:self
shouldChangeCharactersInRange:aRange
replacementString:newString]) {
[super setText:newString];
UITextPosition * const start = [self positionFromPosition:self.beginningOfDocument
offset:newSelectionRange.location];
self.selectedTextRange = [self textRangeFromPosition:start
toPosition:[self positionFromPosition:start
offset:newSelectionRange.length]];
}
return NO;
}
}
if([_realDelegate respondsToSelector:_cmd]) {
return [_realDelegate textField:self
shouldChangeCharactersInRange:aRange
replacementString:aReplacementString];
} else
return YES;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment