Reputation: 1154
When user clicks on UITextFiled the cursor is at starting point, for design purpose its not look good. So, I want to change postion of cursor +5 or from center of UITextField.
I had implemented this code found from Github, Stil its not working. Please help me if you can guide me how to solve this problem.
My code is below
#import "UITextField+Selection.h"
@implementation UITextField (Selection)
- (NSRange)selectedRange
{
UITextPosition* beginning = self.beginningOfDocument;
UITextRange* selectedRange = self.selectedTextRange;
UITextPosition* selectionStart = selectedRange.start;
UITextPosition* selectionEnd = selectedRange.end;
NSInteger location = [self offsetFromPosition:beginning toPosition:selectionStart];
NSInteger length = [self offsetFromPosition:selectionStart toPosition:selectionEnd];
return NSMakeRange(location, length);
}
- (void)setSelectedRange:(NSRange)range
{
UITextPosition* beginning = self.beginningOfDocument;
UITextPosition* startPosition = [self positionFromPosition:beginning offset:range.location];
UITextPosition* endPosition = [self positionFromPosition:beginning offset:range.location + range.length];
UITextRange* selectionRange = [self textRangeFromPosition:startPosition toPosition:endPosition];
[self setSelectedTextRange:selectionRange];
}
#import "UITextField+Selection.h"
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self.nameTextField setSelectedRange:NSMakeRange(5,0)]; // Category method called
}
@end
Upvotes: 0
Views: 1761
Reputation: 88
For designing purpose, You can put Image behind UITextview, and put textview above UIImage view. It will look good for design
Upvotes: -1
Reputation: 789
If you want to have custom position of cursor when user selects UITextField
you need to register for notification that is posted when user selects UITextField
.
So you can add yourself as observer (for example in viewDidLoad
method) via:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldSelected) name:UITextFieldTextDidBeginEditingNotification object:nil];
And then in textFieldSelected
method you can:
- (void)textFieldSelected {
[self.nameTextField setSelectedRange:NSMakeRange(5,0)];
}
Upvotes: 1
Reputation: 591
Instead of moving the cursor you can add padding to the left of the UITextFiled like this for design to look better
UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 20)];
textField.leftView = paddingView;
textField.leftViewMode = UITextFieldViewModeAlways;
Upvotes: 2