iOS - appending string before and after the word - ios

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/

Related

How to change text in UITextView and UITextField

I need to edit my UITextView and when I make these changes I need them to reflect that in my UITextFields. Currently i can use the code below to move whatever text i write into the first UITextField is there a simple way to move each line to a separate UITextField?
Like the image, except the 1, 2 and 3 going to a different UITextField.
-(IBAction)print:(id)sender {
NSString *texto = [[NSString alloc] initWithFormat:#"%# %#",[myTextField text],[myTextView text]];
[myTextField setText:texto];
[myTextView setText:#""];
[myTextView resignFirstResponder];
}
Really, I need to figure this out. Any help will be appreciated.
Have your view controller conform to the UITextViewDelegate protocol.
Next, set the delegate property of your text view to your view controller.
Then, implement - (void)textViewDidChange:(UITextView *)textView, along these lines:
- (void)textViewDidChange:(UITextView *)textView
{
// Set the text for your text fields.
//
// (I'm assuming your code for determining the text to put in the
// text fields works as you intend, so I'm just copying it here.)
NSLayoutManager *layoutManager = [textView layoutManager];
unsigned numberOfLines, index, numberOfGlyphs = [layoutManager numberOfGlyphs];
NSRange lineRange;
for (numberOfLines = 0, index = 0; index < numberOfGlyphs; numberOfLines++)
{
(void) [layoutManager lineFragmentRectForGlyphAtIndex:index
effectiveRange:&lineRange];
index = NSMaxRange(lineRange);
NSString *lineText = [textView.text substringWithRange:lineRange];
[yourArray addObject:lineText];
}
textField1.text=yourArray[0];
textField2.text=yourArray[1];
textField3.text=yourArray[2];
textField4.text=yourArray[3];
textField5.text=yourArray[4];
textField6.text=yourArray[5];
textField7.text=yourArray[6];
}

Add plus symbol that cannot be edited in text field in ios (objective c) [duplicate]

This question already has answers here:
Make UITextField which has a static and attributed prefix
(2 answers)
Closed 8 years ago.
I need to create text field on storyboard with a symbol that will appear but will not be editable.
For example, we have a phone number country code +44. The user can edit 44 but "+" cannot be erased.
Thank you in advance.
I'd recommend setting the "+" as text within a UILabel and setting that label as the leftView of your text field. For example, in Objective-C:
UILabel *plusLabel = [[UILabel alloc] init];
plusLabel.text = #" +";
[plusLabel sizeToFit];
self.textField.leftView = plusLabel;
self.textField.leftViewMode = UITextFieldViewModeAlways;
And in Swift:
let plusLabel = UILabel()
plusLabel.text = " +"
plusLabel.sizeToFit()
textField.leftView = plusLabel
textField.leftViewMode = UITextFieldViewMode.Always
You can use the - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string method on the UITextField's delegate to determine if a specific change to the characters in the text field should be allowed. With that method you can compose the proposed final string by way of - (NSString *)stringByReplacingCharactersInRange:(NSRange)range withString:(NSString *)replacement.
NSString *finalText = [textField.text stringByReplacingCharactersInRange:range withString:string];
Then you can compare that final text string with an empty string, if they are the same, return NO. This assumes your text field's text starts with the "+" in it.
if ([finalString isEqualToString:#""]) {
return NO;
} else {
return YES;
}

hyperlink to section of text in uitextview

I am trying to set up a 'Frequently Asked Questions' section on a UITextView. How do I link a line of text on a UITextView so that when the user clicks on it, the UITextView scrolls to a section of text in the same view. I would also like to underline the text and change the text color to blue.
try TTTAttributedLabel
TTTAttributedLabel allows you to automatically detect links for dates, addresses, links, phone numbers, transit information, or allow you to embed your own.
label.enabledTextCheckingTypes = NSTextCheckingTypeLink; // Automatically detect links when the label text is subsequently changed
label.delegate = self; // Delegate methods are called when the user taps on a link (see `TTTAttributedLabelDelegate` protocol)
label.text = #"Fork me on GitHub! (http://github.com/mattt/TTTAttributedLabel/)"; // Repository URL will be automatically detected and linked
NSRange range = [label.text rangeOfString:#"me"];
[label addLinkToURL:[NSURL URLWithString:#"http://github.com/mattt/"] withRange:range]; // Embedding a custom link in a substring
You need to first fetch the click event of the text "Frequentry asked questions". on the click event you need to make code for scrolling.
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange
{
//Set your character range here
// if match return TRUE .
// else return FALSE.
}
On successful character range fetch scroll your textView to the questions by using this method.
CGPoint bottomOffset;
bottomOffset = CGPointMake(0,(Y value of the question));
[self.chatOutput setContentOffset:bottomOffset animated:YES];
This method will scroll the uitextview to the position of your question.
NSMutableAttributedString * str = [[NSMutableAttributedString alloc] initWithString:#"Google"];
[str addAttribute: NSLinkAttributeName value: #"http://www.google.com" range: NSMakeRange(0, str.length)];
yourTextField.attributedText = str;

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

UITextField has trailing whitespace after secureTextEntry toggle

I have a button that toggles between Show/Hide mode (i.e. toggles a UITextField between secureTextEntry NO and YES). The purpose of which is to allow the user to see the password they are entering.
I followed the example (with the highest number of votes) here: UITextField secureTextEntry - works going from YES to NO, but changing back to YES has no effect
However, when I set secureTextEntry to NO, any text that was written there ends up with a space at the end. This does not seem to be a problem when setting secureTextEntry to YES.
For example, if I enter the text "mypassword" while setSecureTextEntry is set to NO, and then switch it to YES, the user will see ********** (10 dots), which is correct. If I setSecureTextEntry to NO, the user will see "mypassword " (with a space at the end, or at least, the cursor moved one space to the right).
Important note: In the debugger, the string value of text appears without the trailing space, like this:
(lldb) expr self.passwordText.text
(NSString *) $0 = 0x1d8450e0 #"mypassword"
I have tried trimming whitespace (per avoid middle whitespace in UITextField), but it has had no effect.
i've just encounter this case and finally solved this problem.
works on Latest iOS SDK, iOS 8.1
First of all, there is no trailing space at all.
The dot(shown in SecureEntry) character and normal character have different width and after you toggle isSecureEntry switch, the cursor didn't refresh it's position.
so i use this workaround to solved this problem.
- (void)toggle
{
NSString *tmpString;
[self.passwordTextField setSecureTextEntry:!self.passwordTextField.isSecureTextEntry];
if (self.passwordTextField.isSecureTextEntry) {
// do stuffs
} else {
// do other stuffs
}
// Workaround to refresh cursor
tmpString = self.passwordTextField.text;
self.passwordTextField.text = #" ";
self.passwordTextField.text = tmpString;
}
Swift 3+
// Workaround to refresh cursor
let currentText: String = self.userPassword.text!
self.userPassword.text = "";
self.userPassword.text = currentText
hope it helps!
PRE-iOS-8.0 (dated solution)... In your button's action method (toggling between secureTextEntry YES and NO), simply set UITextField's text property to its current text value. Although this may seem redundant and a bit like a hack, this will redraw the cursor in the right position. Here's an example of what your button's action method should look like now...
-(void)toggleButtonPressed:(UIButton*)sender
{
// Toggle between secure and not-so-secure entry
self.toggleButton.selected = !self.toggleButton.selected;
self.textfield.secureTextEntry = !self.toggleButton.selected;
// * Redundant (but necessary) line *
[self.textfield setText:self.textfield.text];
}
POST-iOS-8.0... As of iOS 8.0, it appears that UITextField's text setter no longer redraws the cursor when called with a string equal to its current string value. Now, we need to take this a step further and actually change the text value before resetting it again. Replace the above setText: line with something like these lines.
// * Extra redundant (but necessary) lines *
NSString *currentText = self.textfield.text;
[self.textfield setText:#"Arbitrary string..."]; // Change the value
[self.textfield setText:currentText]; // Reset the value
I have a clean solution not going dirty with text property of UITextField.
Wrap them in this style.
[self.passwordTextField resignFirstResponder]; // first resign its first responder.
// change `secureTextEntry` property's value if necessary.
if (self.passwordTextField.secureTextEntry) {
self.passwordTextField.secureTextEntry = NO;
self.passwordEcryptButton.selected = YES;
}else{
self.passwordTextField.secureTextEntry = YES;
self.passwordEcryptButton.selected = NO;
}
[self.passwordTextField becomeFirstResponder]; // finally gain its first responder again.
In order to work around this bug in iOS you can simply do the following (works for any iOS version):
- (IBAction)toggleSecureTextEntry:(UIButton *)button
{
self.textField.secureTextEntry = !self.textField.secureTextEntry;
NSString *originalText = self.textField.text;
self.textField.text = nil;
self.textField.text = originalText;
}
You can fix it like this:
NSString *currentText = self.textfield.text;
self.textfield.text = #"";
self.textfield.text = currentText;
This work for me on iOS 8
if (self.passwordTextField.secureTextEntry) {
// Display password and keep selected text range
UITextRange *selectedTextRange = self.passwordTextField.selectedTextRange;
NSString *password = self.passwordTextField.text;
self.passwordTextField.secureTextEntry = NO;
self.passwordTextField.text = [#"" stringByPaddingToLength:password.length withString:#" " startingAtIndex:0]; // Done for carret redrawing
self.passwordTextField.text = password;
self.passwordTextField.selectedTextRange = selectedTextRange;
}
else {
// Hide password and keep selected text range
UITextRange *selectedTextRange = self.passwordTextField.selectedTextRange;
NSString *password = self.passwordTextField.text;
self.passwordTextField.secureTextEntry = YES;
self.passwordTextField.text = [#"" stringByPaddingToLength:password.length withString:#" " startingAtIndex:0]; // Done for carret redrawing
self.passwordTextField.text = password;
self.passwordTextField.selectedTextRange = selectedTextRange;
}
UITextPosition *beginning = [self.passwordField beginningOfDocument];
[self.passwordField setSelectedTextRange:[self.passwordField textRangeFromPosition:beginning
toPosition:beginning]];
UITextPosition *end = [self.passwordField endOfDocument];
[self.passwordField setSelectedTextRange:[self.passwordField textRangeFromPosition:end
toPosition:end]];
This is what I used for iOS 8
When we change a textfield.secureTextEntry property, the caret position is not updated. To fix this, the code below used to work before IOS 8:
pwdTextField.text = pwdTextField.text
Now it doesn't. It seems IOS 8 detects the new value equals old value and does nothing. So to make it work again we have to actually change the value. Here is the swift version that works for me.
let str = pwdTextField.text
pwdTextField.text = str + " "
pwdTextField.text = str
This is another possibility to solve this issue, where self.passwordText is the UITextField:
if (self.passwordText.isFirstResponder) {
[self.passwordText resignFirstResponder];
[self.passwordText becomeFirstResponder];
}
It appears that the second solution in the referenced link, when implemented, has the desired behavior of not adding an extra space:
https://stackoverflow.com/a/8495888/738190
This Works in my case
BOOL wasFirstResponder = [self.passwordTextField isFirstResponder];
if([self.passwordTextField isSecureTextEntry])
{
//This three lines are key
self.passwordTextField.delegate = nil;
[self.passwordTextField resignFirstResponder];
self.passwordTextField.delegate = self;
}
[self.passwordTextField setSecureTextEntry: !self.passwordTextField.isSecureTextEntry];
if(wasFirstResponder)
[self.passwordTextField becomeFirstResponder];
Swift UITextField extension:
extension UITextField {
func toggleSecureEntry() {
let wasFirstResponder = isFirstResponder
if wasFirstResponder { resignFirstResponder() }
isSecureTextEntry.toggle()
if wasFirstResponder { becomeFirstResponder() }
}
}
Setting textField.text solution also works in some situations but not for my need (Custom font with two text fields. Caused font changes and glitches on runtime.) Adding here too.
func toggleSecureEntry() {
isSecureTextEntry.toggle()
let originalText = text
text = nil
text = originalText
}
To get the cursor to reposition correctly, setting the font attributes seemed to do the trick for me.
// Hack to update cursor position
self.passwordTf.defaultTextAttributes = #{NSFontAttributeName: textFieldFont, NSForegroundColorAttributeName: textFieldColor};
// Change secure entry
self.passwordTf.secureTextEntry = !self.passwordTf.secureTextEntry;
Tested on iOS8, iOS9.
Hope it helps!
Everytime the text is set in the UITextField, the cursor postition is updated
So I used this code
partial void btnShowPassword_ToutchUpInside (UIButton sender)
{
if (TxtPassword.SecureTextEntry == true) {
TxtPassword.SecureTextEntry = false;
TxtPassword.Text = TxtPassword.Text;
} else {
TxtPassword.SecureTextEntry = true;
}
}
Here is the solution:
- (void)showHidePassword:(UIButton *)sender {
EDSignUpCell *cell = [self.signUpTblView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:3 inSection:0]];
if(!TRIM_SPACE(cell.cellTextField.text).length) {return;}
[cell.showHidePasswordBtn setSelected:!cell.showHidePasswordBtn.isSelected];
cell.cellTextField.secureTextEntry = cell.showHidePasswordBtn.isSelected;
[cell.cellTextField setText:cell.cellTextField.text];
[cell.cellTextField becomeFirstResponder];
}
I'm using this, Works fine.
[self.yourTextField becomeFirstResponder];
Swift 4
Bug is on radar, there is explanation of workaround also: http://www.openradar.me/38465011
Here is cut of temporary workaround how to natively update caret (cursor) position.
// update caret position
DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
let (beginning, end) = (self.beginningOfDocument, self.endOfDocument)
self.selectedTextRange = self.textRange(from: beginning, to: end)
self.selectedTextRange = self.textRange(from: end, to: end)
}
I had a similar issue and realized it was because I was updating the text before setting the secureTextEntry property. It makes sense that the textField would draw out the caret at the location it'd be at if it were using secureTextEntry.
I did not read the entire problem nor did I visit the solution linked by OP, but in case someone else has the same issue as me:
Try updating your text after setting the secureTextEntry property.

Resources