how to move cursor in UITextField after setting its value - ios

can anybody help me with this: i need to implement UITextField for input number. This number should always be in decimal format with 4 places e.g. 12.3456 or 12.3400.
So I created NSNumberFormatter that helps me with decimal places.
I am setting the UITextField value in
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
method.
I proccess input, use formatter and finally call [textField setText: myFormattedValue];
This works fine but this call also moves the cursor to the end of my field. That is unwanted. E.g. I have 12.3400 in my field and the cursor is located on the very beginning and user types number 1. The result value is 112.3400 but cursor is moved at the end. I want to end with cursor when the user expects (just after the number 1 recently added). There are some topics about setting cursor in TextView but this is UITextField. I also tried to catch selectedTextRange of the field, which saves the cursor position properly but after setText method call, this automatically changes and the origin UITextRange is lost (changed to current). hopefully my explanation is clear.
Please, help me with this. thank you very much.
EDIT : Finally, i decided to switch the functionality to changing the format after whole editing and works good enough. I have done it by adding a selector forControlEvents:UIControlEventEditingDidEnd.

After the UITextField.text property is changed, any previous references to UITextPosition or UITextRange objects that were associated with the old text will be set to nil after you set the text property. You need to store what the text offset will be after the manipulation will be BEFORE you set the text property.
This worked for me (note, you do have to test whether cursorOffset is < textField.text.length if you remove any characters from t in the example below):
- (BOOL) textField:(UITextField *) textField shouldChangeCharactersInRange:(NSRange) range replacementString:(NSString *) string
{
UITextPosition *beginning = textField.beginningOfDocument;
UITextPosition *start = [textField positionFromPosition:beginning offset:range.location];
UITextPosition *end = [textField positionFromPosition:start offset:range.length];
UITextRange *textRange = [textField textRangeFromPosition:start toPosition:end];
// this will be the new cursor location after insert/paste/typing
NSInteger cursorOffset = [textField offsetFromPosition:beginning toPosition:start] + string.length;
// now apply the text changes that were typed or pasted in to the text field
[textField replaceRange:textRange withText:string];
// now go modify the text in interesting ways doing our post processing of what was typed...
NSMutableString *t = [textField.text mutableCopy];
t = [t upperCaseString];
// ... etc
// now update the text field and reposition the cursor afterwards
textField.text = t;
UITextPosition *newCursorPosition = [textField positionFromPosition:textField.beginningOfDocument offset:cursorOffset];
UITextRange *newSelectedRange = [textField textRangeFromPosition:newCursorPosition toPosition:newCursorPosition];
[textField setSelectedTextRange:newSelectedRange];
return NO;
}

And here is the swift version :
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let beginning = textField.beginningOfDocument
let start = textField.positionFromPosition(beginning, offset:range.location)
let end = textField.positionFromPosition(start!, offset:range.length)
let textRange = textField.textRangeFromPosition(start!, toPosition:end!)
let cursorOffset = textField.offsetFromPosition(beginning, toPosition:start!) + string.characters.count
// just used same text, use whatever you want :)
textField.text = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)
let newCursorPosition = textField.positionFromPosition(textField.beginningOfDocument, offset:cursorOffset)
let newSelectedRange = textField.textRangeFromPosition(newCursorPosition!, toPosition:newCursorPosition!)
textField.selectedTextRange = newSelectedRange
return false
}

Here is a swift 3 version
extension UITextField {
func setCursor(position: Int) {
let position = self.position(from: beginningOfDocument, offset: position)!
selectedTextRange = textRange(from: position, to: position)
}
}

What actually worked for me was very simple, just used dispatch main async:
DispatchQueue.main.async(execute: {
textField.selectedTextRange = textField.textRange(from: start, to: end)
})

Implement the code described in this answer: Moving the cursor to the beginning of UITextField
NSRange beginningRange = NSMakeRange(0, 0);
NSRange currentRange = [textField selectedRange];
if(!NSEqualRanges(beginningRange, currentRange))
{
[textField setSelectedRange:beginningRange];
}
EDIT: From this answer, it looks like you can just use this code with your UITextField if you're using iOS 5 or above. Otherwise, you need to use a UITextView instead.

Swift X.
To prevent from moving cursor from last position.
func textFieldDidChangeSelection(_ textField: UITextField) {
let point = CGPoint(x: bounds.maxX, y: bounds.height / 2)
if let textPosition = textField.closestPosition(to: point) {
textField.selectedTextRange = textField.textRange(from: textPosition, to: textPosition)
}
}

Related

UITextView change selectRange always crash

When user click the passage in textView, I want to change the cursor to the linebreak, but when I change selectionRange is always failed.
I know the reason, but I must change the selectedRange in func: textViewDidChangeSelection:(UITextView*)textView
How can I change the selectedRange?
here is the code
-(void)textViewDidChangeSelection:(UITextView *)textView
// paragLocations: it contain all "\n" locations
NSArray* paragLocations = [self ParagraphLocationsWithText:textView Pattern:translatePragraphLinebreak];
// location :According to user selection,The nearest "\n" location
NSUInteger nearestLocation = [self ClickParagraphEndBreakLoctionWithSelectLocation:textView.selectedRange.location withParagLocations:paragLocations];
//Then
//1. here I change the textView.selectedRange
textView.selectedRange = NSMakeRange(nearestLocation, 0);
//2. here I change the cursorPosition
CGFloat cursorPosition = [self caretRectForPosition:textView.selectedTextRange.start].origin.y;
[textView setContentOffset:CGPointMake(0, cursorPosition) animated:YES];
// but In step 1 ,It changed textView.selectedRange,So this func will do it again,and then again,until the nearestLocation became the paragLocations.lastObject.
/*
so the question is how to break this Infinite loop ?
should I change selectedRange In this func?
I want to changed the selectedRange base on User select In textview
*/
sorry about my poor english.
You can try the following code, it works for me fine.
- (void)textViewDidChangeSelection:(UITextView *)textView {
UITextRange *selectRange = [textView selectedTextRange];
NSString *selectedText = [textView textInRange:selectRange];
}

How do I add an unordered list or a bullet point every new line in a UITextView

So basically I want to add an unordered list to a UITextView. And to another UITextView I want to add an ordered list.
I tried using this code, but it only gave me a bullet point after the first time the user presses enter, (not any more than that,) and I can't even backspace it.
- (void)textViewDidChange:(UITextView *)textView
{
if ([myTextField.text isEqualToString:#"\n"]) {
NSString *bullet = #"\u2022";
myTextField.text = [myTextField.text stringByAppendingString:bullet];
}
}
If you only find a way performing it with Swift then feel free to post a Swift version of the code.
The problem is that you're using
if ([myTextField.text isEqualToString:#"\n"]) {
as your conditional, so the block executes if the entirety of your myTextField.text equals "\n". But the entirety of your myTextField.text only equals "\n" if you haven't entered anything but "\n". That's why right now, this code is only working "the first time the user presses enter"; and when you say "I can't even backspace it," the problem is actually that the bullet point's being re-added with the call to textViewDidChange: since the same conditional is still being met.
Instead of using textViewDidChange: I recommend using shouldChangeTextInRange: in this case so you can know what that replacement text is no matter it's position within the UITextView text string. By using this method, you can automatically insert the bullet point even when the newline is entered in the middle of the block of text... For example, if the user decides to enter a bunch of info, then jump back up a few lines to enter some more info, then tries to press newline in between, the following should still work. Here's what I recommend:
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
// If the replacement text is "\n" and the
// text view is the one you want bullet points
// for
if ([text isEqualToString:#"\n"]) {
// If the replacement text is being added to the end of the
// text view, i.e. the new index is the length of the old
// text view's text...
if (range.location == textView.text.length) {
// Simply add the newline and bullet point to the end
NSString *updatedText = [textView.text stringByAppendingString:#"\n\u2022 "];
[textView setText:updatedText];
}
// Else if the replacement text is being added in the middle of
// the text view's text...
else {
// Get the replacement range of the UITextView
UITextPosition *beginning = textView.beginningOfDocument;
UITextPosition *start = [textView positionFromPosition:beginning offset:range.location];
UITextPosition *end = [textView positionFromPosition:start offset:range.length];
UITextRange *textRange = [textView textRangeFromPosition:start toPosition:end];
// Insert that newline character *and* a bullet point
// at the point at which the user inputted just the
// newline character
[textView replaceRange:textRange withText:#"\n\u2022 "];
// Update the cursor position accordingly
NSRange cursor = NSMakeRange(range.location + #"\n\u2022 ".length, 0);
textView.selectedRange = cursor;
}
// Then return "NO, don't change the characters in range" since
// you've just done the work already
return NO;
}
// Else return yes
return YES;
}
Just in case, anyone was looking for a Swift 2.x solution to the same problem, here's a solution:
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
// If the replacement text is "\n" and the
// text view is the one you want bullet points
// for
if (text == "\n") {
// If the replacement text is being added to the end of the
// text view, i.e. the new index is the length of the old
// text view's text...
if range.location == textView.text.characters.count {
// Simply add the newline and bullet point to the end
var updatedText: String = textView.text!.stringByAppendingString("\n \u{2022} ")
textView.text = updatedText
}
else {
// Get the replacement range of the UITextView
var beginning: UITextPosition = textView.beginningOfDocument
var start: UITextPosition = textView.positionFromPosition(beginning, offset: range.location)!
var end: UITextPosition = textView.positionFromPosition(start, offset: range.length)!
var textRange: UITextRange = textView.textRangeFromPosition(start, toPosition: end)!
// Insert that newline character *and* a bullet point
// at the point at which the user inputted just the
// newline character
textView.replaceRange(textRange, withText: "\n \u{2022} ")
// Update the cursor position accordingly
var cursor: NSRange = NSMakeRange(range.location + "\n \u{2022} ".length, 0)
textView.selectedRange = cursor
}
return false
}
// Else return yes
return true
}
Swift 5.x version.
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
//
// If the replacement text is "\n" and the
// text view is the one you want bullet points
// for
if (text == "\n") {
// If the replacement text is being added to the end of the
// text view, i.e. the new index is the length of the old
// text view's text...
if range.location == textView.text.count {
// Simply add the newline and bullet point to the end
let updatedText: String = textView.text! + "\n \u{2022} "
textView.text = updatedText
}
else {
// Get the replacement range of the UITextView
let beginning: UITextPosition = textView.beginningOfDocument
let start: UITextPosition = textView.position(from: beginning, offset: range.location)!
let end: UITextPosition = textView.position(from: start, offset: range.length)!
let textRange: UITextRange = textView.textRange(from: start, to: end)!
// Insert that newline character *and* a bullet point
// at the point at which the user inputted just the
// newline character
textView.replace(textRange, withText: "\n \u{2022} ")
// Update the cursor position accordingly
let cursor: NSRange = NSMakeRange(range.location + "\n \u{2022} ".count, 0)
textView.selectedRange = cursor
}
return false
}
// Else return yes
return true
}

setBaseWritingDirection: on UITextField does not work

I'm trying to configure an UITextField for Right-To-Left writing. I Can't get it to work. The problem starts with the required UITextRange parameter for setBaseWritingDirection, I will always get nil as return value.
textfield.text = #"hello world";
UITextPosition * startpos =[textfield beginningOfDocument]; // returns nil! why?
UITextPosition *endpos =[textfield endOfDocument]; // returns nil
UITextRange* range =[textfield textRangeFromPosition:startpos toPosition:endpos] ; // returns nil
[textfield setBaseWritingDirection:UITextWritingDirectionRightToLeft forRange: range ]; // does not work, range is nil
If I change the UItextField to an UITextView, the beginningOfDocument and endOfDocument method return a UITextPosition object.
Is that not implemented on UITextFields or am I doing something wrong?

iOS - appending string before and after the word

I want to add a string in the highlighted area in the textview, I mean by the highlighted area, where the blue line is located.
So once the user click on the button it adds a string where the "blue line" is located
I used stringByAppendingString but it adds the string after the word exists only
NSRange range = myTextView.selectedRange;
NSString * firstHalfString = [myTextView.text substringToIndex:range.location];
NSString * secondHalfString = [myTextView.text substringFromIndex: range.location];
myTextView.scrollEnabled = NO; // turn off scrolling
NSString * insertingString = [NSString stringWithFormat:#"your string value here"];
myTextView.text = [NSString stringWithFormat: #"%#%#%#",
firstHalfString,
insertingString,
secondHalfString];
range.location += [insertingString length];
myTextView.selectedRange = range;
myTextView.scrollEnabled = YES;
You need to use the selectedRange to find out where the text cursor is. Then use replaceCharactersInRange:withString: or insertString:atIndex: to insert the new text into the original text. Then update the text into the view.
Even though its not clear what you are trying to achieve, it seems that you want the user to start editing the textfield from the position where text starts. In that case , you can refer following:
Hint 1
Set your view controller (or some other appropriate object) as the text field's delegate and implement the textFieldDidBeginEditing: method like this:
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
UITextPosition *beginning = [textField beginningOfDocument];
[textField setSelectedTextRange:[textField textRangeFromPosition:beginning
toPosition:beginning]];
}
Note that setSelectedTextRange: is a protocol method of UITextInput (which UITextField implements), so you won't find it directly in the UITextField documentation.
Hint 2
self.selectedTextRange = [self textRangeFromPosition:newPos toPosition:newPos];
Hint 3
finding-the-cursor-position-in-a-uitextfield/

UITextPosition to Int

I have a UISearchBar on which I am trying to set a cursor position. I am using UITectField delegates as I couldn't find anything direct for UISearchBar. Below is the code I am using:
UITextField *textField = [searchBar valueForKey: #"_searchField"];
// Get current selected range , this example assumes is an insertion point or empty selection
UITextRange *selectedRange = [textField selectedTextRange];
// Construct a new range using the object that adopts the UITextInput, our textfield
UITextRange *newRange = [textField textRangeFromPosition:selectedRange.start toPosition:selectedRange.end];
Question is in the 'newRange' object for 'toPosition' I want to have something like selectedRange.end-1; as I want the cursor to be on second last position.
How do I set the cursor to second last position?
Swift 5
I came across this question originally because I was wondering how to convert UITextPosition to an Int (based on your title). So that is what I will answer here.
You can get an Int for the current text position like this:
if let selectedRange = textField.selectedTextRange {
// cursorPosition is an Int
let cursorPosition = textField.offset(from: textField.beginningOfDocument, to: selectedRange.start)
}
Note: The properties and functions used above are available on types that implement the UITextInput protocol so if textView was a UITextView object, you could replace the instances of textField with textView and it would work similarly.
For setting the cursor position and other related tasks, see my fuller answer.
the clue is to make a position and then a range with no length and then select it
e.g.
- (IBAction)select:(id)sender {
//get position: go from end 1 to the left
UITextPosition *pos = [_textField positionFromPosition:_textField.endOfDocument
inDirection:UITextLayoutDirectionLeft
offset:1];
//make a 0 length range at position
UITextRange *newRange = [_textField textRangeFromPosition:pos
toPosition:pos];
//select it to move cursor
_textField.selectedTextRange = newRange;
}

Resources