我的iPhone应用程序中有一个UITextField。我知道如何让文本字段选择它的所有文本,但是如何更改选择?假设我想选择最后5个字符,或者特定的字符范围,这是可能的吗?如果没有,我是否可以移动标记选择的开始和结束的线,就像用户正在拖动它们一样?
发布于 2010-07-19 12:31:15
使用UITextField,您就不能这样做。但是如果你看到标题,你有_selectedRange和其他的,如果你添加了一些类别,你可能会用到它们;)
iOS5及更高版本的更新:
现在,UITextField和UITextView符合UITextInput协议,因此可以:)
选择插入符号前的最后5个字符如下所示:
// Get current selected range , this example assumes is an insertion point or empty selection
UITextRange *selectedRange = [textField selectedTextRange];
// Calculate the new position, - for left and + for right
UITextPosition *newPosition = [textField positionFromPosition:selectedRange.start offset:-5];
// Construct a new range using the object that adopts the UITextInput, our textfield
UITextRange *newRange = [textField textRangeFromPosition:newPosition toPosition:selectedRange.start];
// Set new range
[textField setSelectedTextRange:newRange];发布于 2013-01-06 03:00:07
要选择特定范围的字符,可以在iOS 5+中执行以下操作
int start = 2;
int end = 5;
UITextPosition *startPosition = [self positionFromPosition:self.beginningOfDocument offset:start];
UITextPosition *endPosition = [self positionFromPosition:self.beginningOfDocument offset:end];
UITextRange *selection = [self textRangeFromPosition:startPosition toPosition:endPosition];
self.selectedTextRange = selection;因为UITextField和其他UIKit元素有自己的私有子类UITextPosition和UITextRange,所以不能直接创建新值,但可以使用文本字段从对文本开头或结尾的引用和整数偏移量创建它们。
也可以进行相反操作,以获取当前选择的起点和终点的整数表示形式:
int start = [self offsetFromPosition:self.beginningOfDocument toPosition:self.selectedTextRange.start];
int end = [self offsetFromPosition:self.beginningOfDocument toPosition:self.selectedTextRange.end];下面是一个类别,其中添加了使用NSRanges. https://gist.github.com/4463233处理选择的方法。
发布于 2013-12-11 23:12:35
要选择不带文件扩展名的文件名,请使用以下命令:
-(void) tableViewCellDidBeginEditing:(UITableViewTextFieldCell*) cell
{
NSInteger fileNameLengthWithoutExt = [self.filename length] - [[self.filename pathExtension] length];
UITextField* textField = cell.textField;
UITextPosition* start = [textField beginningOfDocument];
UITextPosition* end = [textField positionFromPosition:start offset: fileNameLengthWithoutExt - 1]; // the -1 is for the dot separting file name and extension
UITextRange* range = [textField textRangeFromPosition:start toPosition:end];
[textField setSelectedTextRange:range];
}https://stackoverflow.com/questions/3277538
复制相似问题