How to programmatically enter text in UITextView at the current cursor position - ios

I would like to add (some predefined) text at the current cursor position in a UITextView using Swift. So if I have a UITextField named txtField that has some text in it already such as "this is a beautiful valley" and I tap in the area between "a" and "beautiful" so that the cursor is now in the space between "a" and "beautiful" and then click a Button on my user interface a string of text such as "very" will get typed at the cursor position, so that the text in the UITextView will now become "this is a very beautiful valley". At the end of this operation (after button click event) I would the cursor to be just after the word "very". Many thanks for your help. I can see some question on the forum with similar themes, but the answers are in Objective C. I suicidal like help using Swift.

Try this... Inside your button's IBAction use this (please do not use forced optional unwrapping) or else if the textView has no selection or cursor, the app might crash:
let txt = "whatever you want"
if let range = handleToYourTextView.selectedTextRange {
// From your question I assume that you do not want to replace a selection, only insert some text where the cursor is.
if range.start == range.end {
handleToYourTextView.replaceRange(range, withText: txt)
}
}

try this
textView.replaceRange(textView.selectedTextRange!, withText: "your text")

update:
Swift 5.2
let txt = "whatever you want"
if let range = myTextView.selectedTextRange {
if range.start == range.end {
myTextView.replace(range, withText: txt)
}

Related

Inserting (Appending) text on the top of a UITextView - Swift

I have a UITextView where I insert text using:
MyUITextView.insertText(my_string_to_be_inserted)
it works fine but it appends text to the bottom of the UITextView.
Is there any way to add text on the top (like a stack) where the last added text will be always on the top?
You can try the snippet below.
if let position = textView.textRange(from: textView.beginningOfDocument, to: textView.beginningOfDocument) {
textView.replace(position, withText: "Your text goes here")
}
Refer the api here.

Swift 4 UiTextView - delete a word inside textView on button click

Is there a way to delete a specific word inside a UITextView?
let's say for example that in a textView the user wrote: "Hello my nome is john".
As soon as he finished typing he noticed that he mistyped a word.
Lets' say that there is an array initialised with a set o word and "name" is one of this.
when the user go back with the cursor and start deleting the misspelled a list of suggestion comes up.
He detect the word name and click on it.
is there a way to delete the word nome and insert the word name on which he just clicked.
So basically is there a way to get the word immediately before the cursor and remove it from the text view?
I have been able to get the first word before the cursor:
func characterBeforeCursor() -> String? {
// get the cursor position
if let cursorRange = postTextField.selectedTextRange {
// get the position one character before the cursor start position
if let newPosition = postTextField.position(from: cursorRange.start, offset: -1) {
let range = postTextField.textRange(from: newPosition, to: cursorRange.start)
return postTextField.text(in: range!)
}
}
return nil
}
but i wouldn't know how to get the entire word (until the first space, or a particular character e.g "#" ) and delte it from the textview.
I am a bit lost.... so Thanks to anyone will help.

UITextField's width is never less than it's width with placeholder text

I have a UITextField and UILabel sitting together in a UIView as so:
and here it is in Xcode:
The label is hidden until the user enters some text into the text field, so it serves to provide a persistent "suffix" to the numeric entry. The problem is that when the user types a number into the text field, it doesn't shrink down to the size of the text, it remains at the size of the original placeholder, even though it isn't visible, as so:
Is there any way I can constrain the text field's width to be the minimum size to accommodate the user's text, and not pay attention to the invisible placeholder text's width?
Thank you
I managed to solve it myself:
Whenever the text is edited, the text field is checked to see if there is any text inside. If there is no text, the 'mg' suffix is hidden, and the placeholder is added. If there is text, the 'mg' suffix is shown and the placeholder is removed. Like so: (Swift)
func textFieldTextChanged(_ textField: UITextField) {
milligramTextField.invalidateIntrinsicContentSize()
view.layoutIfNeeded()
if textField.text == "" {
milligramSuffixLabel.text = ""
milligramTextField.placeholder = "0 mg"
} else {
milligramSuffixLabel.text = " mg"
milligramTextField.placeholder = ""
}
}
This answer was of great help.

How can I move the cursor to the beginning of a UITextField in Swift?

I have seen this question asked many times, but every answer seems to be written in objective c, which I do not know nor do I know how to convert to Swift.
I have a text field where I want a user to input a percentage.
I have it so that when they start editing the text box, the placeholder text disappears and is replaced with a percentage sign.
I want this percentage sign to always remain at the end of the input. I can't seem to figure out how to move the cursor back to the beginning of the text box to achieve this.
Here's the code for my begin editing action (this includes another text box where the user inputs a dollar amount, but the dollar sign comes first so that's no big deal)
#IBAction func textBoxBeginEditing(sender: UITextField) {
// Dismiss keyboard if the main view is tapped
tapRecognizer.addTarget(self, action: "didTapView")
view.addGestureRecognizer(tapRecognizer)
// If there's placeholder text, remove it and change text color to black
if (sender.textColor == UIColor.lightGrayColor()) {
sender.text = nil
sender.textColor = UIColor.blackColor()
}
// Force the keyboard to be a number pad
sender.keyboardType = UIKeyboardType.NumberPad
// Set up symbols in text boxes
if (sender == deductibleTextBox) {
sender.text = "$"
}
if (sender == percentageTextBox) {
sender.text = "%"
// This part doesn't do anything... Need a solution
let desiredPosition = sender.beginningOfDocument
sender.selectedTextRange = sender.textRangeFromPosition(desiredPosition, toPosition: desiredPosition)
}
}
That last bit was all I got from the internet for help. This app I am creating has been quite the iOS learning curve, so I apologize if this is a dumb question.
let newPosition = textView.beginningOfDocument
textView.selectedTextRange = textView.textRangeFromPosition(newPosition, toPosition: newPosition)
In this we are getting the beginning of the textview and then setting the selected both to the beginning.

Selecting a word and shows tooltip in iOS

I would like to implement the Medium iOS App like effect for tapping highlight and shows tooltip.
I have been researching on Text Kit and some other stackoverflow questions have some thoughts on it, please also suggest what's the better alternative to this.
Scenario:
Static Text pre-defined
Shows highlights in several words or phrases
Solution thoughts:
Use UITextView for storing text
Use attributed string for text content
Showing background color using NSBackgroundColorAttributedName
Detect the selection by layoutManager.characterIndexForPoint(...)
Shows tooltip next to the selection
Shows tooltip using one of these pods AMPopTip, CMPopTipView, EasyTipView
Right now, I am not able to select the word and shows the tooltip just next to it. Any tier of help is appreciated.
Here is a way to Highlight text.
Create an IBOutlet named myLabel
In ViewDidLoad type
let yourString = "This is how you highlight text"
myLabel.text = yourString
let malleableString = NSMutableAttributedString(string: yourString)
let numberOfCharactersToHighlight = 5
let startingIndex = 1
malleableString.addAttribute(NSBackgroundColorAttributeName, value: .magenta, range: NSRange(location: startingIndex, length: numberOfCharactersToHighlight))
myLabel.attributedText = malleableString

Resources