How to change the starting cursor position inside UITextView - ios

I have a uitextview which become the first responder on viewload. but i want to change the position of the cursor of the uitextview at certain position in x for the first 2 line only.

Maybe you could use a UITextKit (a very good tutorial).
For example to have a rounded text you can use something like:
UIBezierPath* exclusionPath = [UIBezierPath bezierPathWithOvalInRect:yourTextView.bounds];
exclusionPath = [exclusionPath bezierPathByReversingPath];
yourTextView.textContainer.exclusionPaths = #[exclusionPath];

Have you tried following solutions ?
Controlling cursor position in a UITextField is complicated because so many abstractions are involved with input boxes and calculating positions. However, it's certainly possible. You can use the member function setSelectedTextRange:
[input setSelectedTextRange:[input textRangeFromPosition:start toPosition:end]];
Here's a function which takes a range and selects the texts in that range. If you just want to place the cursor at a certain index, just use a range with length 0:
+ (void)selectTextForInput:(UITextField *)input atRange:(NSRange)range {
UITextPosition *start = [input positionFromPosition:[input beginningOfDocument]
offset:range.location];
UITextPosition *end = [input positionFromPosition:start
offset:range.length];
[input setSelectedTextRange:[input textRangeFromPosition:start toPosition:end]];
}
For example, to place the cursor at idx in the UITextField input:
[Helpers selectTextForInput:input
atRange:NSMakeRange(idx, 0)];
Source: https://stackoverflow.com/a/11532718/914111
Have not tested due to some busy so please let us know wether it is working or not (May have issue in IOS8.0)

Related

Find text in array and return index number

I am displaying an array of strings separated by \n or linebreaks in a textview. Thanks to the \n, if there is room in the textview, each string gets its own line. However, if the width of the textview is less than the string, then the textview automatically wraps the line to the next line so that the string in effect takes two lines. Nothing wrong with this so far.
However, I want to grab the string if someone touches it. It works fine if the string fits on a line. However, if the string has been broken across two lines by textview, if the user touches the top line, I need to attach the line below to get the whole string. Or if the user touches the bottom line, I need to get and add the previous one to have a whole string.
Can anyone suggest proper way to do this?
Here is my code that grabs the line the person touches, however, it only gets the line touched and fails when it tries to calculate the index of the string in the array.
Thanks for any suggestions:
- (void) handleTap:(UITapGestureRecognizer *)recognizer{
UITextView *textView = (UITextView *)recognizer.view;
CGPoint location = [recognizer locationInView:textView];
CGPoint position = CGPointMake(location.x, location.y);
UITextPosition *tapPosition = [textView closestPositionToPoint:position];
UITextRange *textRange = [textView.tokenizer rangeEnclosingPosition:tapPosition withGranularity:UITextGranularityLine inDirection:UITextLayoutDirectionRight];
//In following line, I am not getting the full text in the string, only the text of that line. I need to get the whole string.
NSString *tappedLine = [textView textInRange:textRange];
NSArray* myArray = [self.listSub.text componentsSeparatedByString:#"\n"];
NSInteger indexOfTheObject = [myArray indexOfObject: tappedLine];
//If the tapped line is not the same thing as the string, the above index becomes huge number like 94959494994949494 ie an error, not the index I want.
}
This is indeed possible.
First, you need to change the granularity to UITextGranularityParagraph:
UITextRange *textRange = [textView.tokenizer rangeEnclosingPosition:tapPosition withGranularity:UITextGranularityParagraph inDirection:UITextLayoutDirectionRight];
This will return you the entire wrapped line of text that the user tapped, no matter where they tapped it.
However, this text will include the trailing \n character that marks the end of the paragraph. You need to remove this before comparing the text to your array. Replace the last line of your code above with these two lines:
NSString *trimmedLine = [tappedLine stringByTrimmingCharactersInSet:
[NSCharacterSet newlineCharacterSet]];
NSInteger indexOfTheObject = [myArray indexOfObject: trimmedLine];
You may want to look into using a UITableView
https://developer.apple.com/documentation/uikit/uitableview
you could create a cell with a text view for each entry in the array and you will get delegate calls when a user interacts with any of the cells

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;
}

How do i make Circled numbers in UITextView

Please Help..im not sure were to begin
..How do i show numbers with circles around them in my UITextView
like 1 2 3 4 .............but each number inside a circle eg http://openclipart.org/people/gsagri04/GS_Numbers.svg
i was hopping to get numbers from an array and show them on screen ....but each number living inside a circle like lotto numbers
# the moment i only have a An array [1,2,3,4],...A button .....and UItextView to show the final output
xcode 4.
If I understood your need correctly, you want to display following special characters in your textview:
① ② ③ ④ ⑤ ⑥ ⑦ ⑧ ⑨ ⑩ ⑪ ⑫ ⑬ ⑭ ⑮ ⑯ ⑰ ⑱ ⑲ ⑳
The easiest approach is to copy+paste these characters, and replace the numeric characters in the content string you need to display in the textview. You may write a NSString category method to handle this job, in sake of code reuse.
#Chris Chen's solution is pretty nifty, as you can change the characters on the go. But if you do not want to use the characters, you may use the following code to add circles to your textView.
UITextPosition *pos = textView.endOfDocument;// textView ~ UITextView
for (int i=0;i<words*2-1;i++){// *2 since UITextGranularityWord considers a whitespace to be a word, words = number of words in the textView.
UITextPosition *pos2 = [textView.tokenizer positionFromPosition:pos toBoundary:UITextGranularityWord inDirection:UITextLayoutDirectionLeft];
UITextRange *range = [textView textRangeFromPosition:pos toPosition:pos2];
CGRect resultFrame = [textView firstRectForRange:(UITextRange *)range ];
if (check whether word at this text position is a number){
UIView* circleView = [[UIView alloc] initWithFrame:resultFrame];
circleView.backgroundColor = [UIColor clearColor];
circleView.layer.borderColor = <color of your choice, probably same as text color>;
circleView.layer.borderWidth = <the width you want to set the border thickness to>;
circleView.layer.cornerRadius = <a float value that makes the rectangle look like a circle>;
circleView .tag = 125;
[textView circleView ];
}
pos = pos2;
}
The code should be placed in the UITextView delegate method textViewDidChange. And make sure you remove the circle view before all this code, hence the tag(125).

iOS: sizeWithFont for single character is different than in a string?

I am trying to determine the precise position of a character in a UILabel, say:
(UILabel *)label.text = #"Hello!";
I'd like to determine the position of the 'o'. I thought that I could just sum the widths of all the preceding characters (or the whole preceding string) using sizeWithFont. The width value I get though is bigger by about 10% than what it should be. Summing the widths of individual letters (i.e. [#"H" sizeWithFont...] + [#"e" sizeWithFont...] + l... + l...) accumulates more error than [#"Hell" sizeWithFont...].
Is there a way of accurately determining the position of a single glyph in a string?
Many thanks.
Yes, but not in a UILabel and not using sizeWithFont:.
I recently worked with Apple Developer Support, and apparently sizeWithFont: is actually an approximation. It becomes less accurate when your text (1) wraps across multiple lines and (2) contains non-latin characters (i.e. Chinese, Arabic), both of which cause line spacing changes not captured by sizeWithFont:. So, don't rely on this method if you want 100% accuracy.
Here are two things you can do:
(1) Instead of UILabel, use a non-editable UITextView. This will support the UITextInput protocol method firstRectForRange:, which you can use to get the rect of the character you need. You could use a method like this one:
- (CGRect)rectOfCharacterAtIndex:(NSUInteger)characterIndex inTextView:(UITextView *)textView
{
// set the beginning position to the index of the character
UITextPosition *beginningPosition = [textView positionFromPosition:textView.beginningOfDocument offset:characterIndex];
// set the end position to the index of the character plus 1
UITextPosition *endPosition = [textView positionFromPosition:beginningPosition offset:1];
// get the text range between these two positions
UITextRange *characterTextRange = [textView textRangeFromPosition:beginningPosition toPosition:endPosition]];
// get the rect of the character
CGRect rectOfCharacter = [textView firstRectForRange:characterTextRange];
// return the rect, converted from the text input view (unless you want it to be relative the text input view)
return [textView convertRect:rectOfCharacter fromView:textView.textInputView];
}
To use it, (assuming you have a UITextView called myTextView already on the screen), you would do this:
myTextView.text = #"Hello!";
CGRect rectOfOCharacter = [self rectOfCharacterAtIndex:4 inTextView:myTextView];
// do whatever you need with rectOfOCharacter
Only use this method for determining the rect for ONE character. The reason for this is that in the event of a line break, firstRectForRange: only returns the rect on the first line, before the break.
Also, consider adding the method above as a UITextView category if you're gong to be using it a lot. Don't forget to add error handling!
You can learn more about how firstRectForRange: works "under the hood" by reading the Text, Web, and Editing Programming Guide for iOS.
(2) Create your own UILabel by subclassing UIView and using Core Text to render the strings. Since you're doing the rendering, you'll be able to get the positions of characters. This approach is a lot of work, and only worthwhile if you really need it (I, of course, don't know the other needs of your app). If you aren't sure how this would work, I suggest using the first approach.
Well fonts are smart now a day and take in respect the position of a character to its pervious character.
Here is an example on how the starting position of the letter o:
NSRange posRange = [hello rangeOfString:#"o"];
NSString *substring = [hello substringToIndex:posRange.location];
CGSize size = [substring sizeWithFont:[UIFont systemFontOfSize:14.0f]];
No you can do the same for the string including the letter o and substract the size found in the string without the letter o.
THis should give the an nice start position of the letter and the size.
in ios6 you can do using attributed string
NSMutableAttributedString *titleText2 = [[NSMutableAttributedString alloc] initWithString:strHello];
NSRange posRange = [hello rangeOfString:#"o"];
[titleText2 addAttributes:[NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:14.0f] forKey:NSFontAttributeName] range:NameRange];
and set your textView with this attributed string

Resources