gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 21:39:51 24 4
gpt4 key购买 nike

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

我已经实现了从 Github 上找到的这段代码,但仍然无法正常工作。如果你能指导我如何解决这个问题,请帮助我。

我的代码如下

#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

最佳答案

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

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

关于ios - 如何设置 UITextField 的自定义光标位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32601324/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com