Skip to content

Instantly share code, notes, and snippets.

@sey
Created February 6, 2014 23:02
Show Gist options
  • Save sey/8854288 to your computer and use it in GitHub Desktop.
Save sey/8854288 to your computer and use it in GitHub Desktop.
UITextField cursor positioning
//
// NFViewController.m
// TextFieldTest
//
// Created by Florian Sey on 06/02/14.
// Copyright (c) 2014 NeoFacto. All rights reserved.
//
#import "NFViewController.h"
@interface NFViewController ()
<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *textField;
@property (nonatomic, assign) NSUInteger position;
@end
@implementation NFViewController
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
self.textField.text = @"abcdefghijklmnopqrstuvwxyz";
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(textFieldDidChange:)
name:UITextFieldTextDidChangeNotification
object:nil];
}
- (void)textFieldDidChange:(NSNotification *)note
{
UITextField *textField = note.object;
[NFViewController selectTextForInput:textField atRange:NSMakeRange(self.position, 0)];
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if ([string isEqualToString:@""])
{
self.position = range.location;
}
else
{
if (range.length <= string.length)
{
self.position = range.location + string.length;
}
else
{
self.position = range.location - string.length + range.length;
}
}
return YES;
}
+ (void)selectTextForInput:(UITextField *)input atRange:(NSRange)range {
UITextPosition *start = [input positionFromPosition:[input beginningOfDocument]
offset:range.location];
UITextPosition *end = [input positionFromPosition:start
offset:range.length];
[input setSelectedTextRange:[input textRangeFromPosition:start toPosition:end]];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment