Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
488 views
in Technique[技术] by (71.8m points)

iphone - Can I select a specific block of text in a UITextField?

I have a UITextField in my iPhone app. I know how to make the text field select all of its text, but how can change the selection? Say I wanted to select the last 5 characters, or a specific range of characters, is that possible? if not, can I move the lines marking the beginning and end of the selection, as if the user is dragging them?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

With UITextField, you cannot. But if you see the headers, you have _selectedRange and others that might be used if you add some categories to it ;)


Update for iOS5 and above :

Now UITextField and UITextView conform to UITextInput protocol so it is possible :)

Selecting the last 5 characters before the caret would be like this:

// 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];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...