如何设置UITextField的自定义光标位置?

时间:2015-09-16 06:36:56

标签: ios objective-c uitextfield

当用户点击UITextFiled时,光标位于起始点,出于设计目的,它看起来不太好。所以,我想改变游标+5的位置或从UITextField的中心。

我已经实现了从Github找到的代码,Stil无法正常工作。如果您可以指导我如何解决这个问题,请帮助我。

我的代码在

下面
#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

3 个答案:

答案 0 :(得分:2)

您可以在UITextFiled的左侧添加填充,而不是移动光标,以便设计看起来更好

UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 20)];
textField.leftView = paddingView;
textField.leftViewMode = UITextFieldViewModeAlways;

答案 1 :(得分:1)

如果您想在用户选择UITextField时拥有光标的自定义位置,则需要注册用户选择UITextField时发布的通知。

所以你可以通过以下方式将自己添加为观察者(例如在viewDidLoad方法中):

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldSelected) name:UITextFieldTextDidBeginEditingNotification object:nil];

然后在textFieldSelected方法中你可以:

- (void)textFieldSelected {
    [self.nameTextField setSelectedRange:NSMakeRange(5,0)];
}

答案 2 :(得分:-1)

出于设计目的,您可以将Image放在UITextview后面,并将textview放在UIImage视图上方。它看起来很适合设计