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

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.

Related

swift how to get UILabel align to top left

I'm making a trivia app that prints the question out word by word, and currently it starts at the middle of the UILabel and pushes the previous text upward. I'm trying to find out if I can start the first word at the top left of the label, the continue printing the rest.
func printQuestion ()
{
var str = quizbrain.getQuestionText()
var arr = str.components(separatedBy: " ")
var count = 0
Timer.scheduledTimer(withTimeInterval: 0.25, repeats: true) { (t) in
self.questionLabel.text! += " " + arr[count]
count += 1
if count == arr.count {
t.invalidate()
}
if self.hasBuzzed == true {
t.invalidate()
}
}
I'm trying to find out if I can start the first word at the top left of the label
No, you can’t. That’s not how labels draw when their text changes.
Cool workaround: start with the label containing the whole text, but use an attributed string so that the text is the same color as the background (e.g. white on white) and thus invisible. In your timer, change the color of one word at a time to black.
That way, you never change the text, just the color, so the text does not move as each word is revealed.

creating spaces in placeholder fields

my problem is I want to put 2 placeholders for one textField. one of the place holders should be on the left and the other should be on the right.
my code:
func returnPlaceHolder(first: String, second: String, textField: UITextField){
let width: Int = Int(textField.bounds.width * 0.2)
let spaceValue = width - (first.count + second.count)
var temp = "\(first) "
let tempCount = spaceValue - (first.count + second.count)
var value = String()
for _ in 0..<tempCount {
temp.append(" ")
}
value = "\(temp) \(second)"
textField.placeholder = value
textField.setLeftPaddingPoints(10)
textField.setRightPaddingPoints(10)
}
I'm currently using this function to create spaces.. but my problem is the spaces won't be the same for more than one textField, and I want them to be aligned..
just like this picture: https://imgur.com/pZZMoNv
and this is the result I'm getting for my current code: https://imgur.com/a/5AN8EXl
don't mind the textFields format & text I can fix them later.. I just want to be able to align the textFields placeholders.
It would be really hard (if possible) to achieve what you are trying to do by injecting spaces into the text because each character in the font has a different width unless you use a monospaced font.
https://en.wikipedia.org/wiki/Monospaced_font
Instead, I would recommend a different approach. Override the text field, provide two UILabels and adjust their position using Autolayout.

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.

Can't set cursor position in UITextView

I'm working on an app that is highly dependent on UITextView. My ideal behavior is when a user quickly presses a double space, the text cursor will jump ahead 5 spaces to make space for a UIButton. I've implemented the following code, but the cursor doesn't seem to jump even though all the other actions in the "quickSpace" area happen. Anyone know what I am doing wrong?
UPDATE: I think the problem is that I am trying to jump the cursor to a point outside of the range that currently exists. In other words, someone is entering new text into the UITextView and the range is set to wherever the cursor happens to be. Is that the end of the range? Is it possible to send a cursor outside of the range that currently exists?
if(text==" "){
let now=Date()
if let last=previousSpaceTimestamp
{
if now.timeIntervalSince(last)<0.3
{
//mainTextBox.text=textView.text.appending("hello")
isQuickSpace=true
var checkOffButton: UIButton=createCheckButton()
checkOffButton.backgroundColor=UIColor.green
checkOffButton.frame.size=CGSize(width: 20, height: 20)
//checkOffButton.frame.offsetBy(dx: 0, dy: CGFloat(buttonYPos))
mainTextBox.addSubview(checkOffButton)
buttonYPos=buttonYPos+15
if let currentRange=mainTextBox.selectedTextRange
{
if let newPosition=mainTextBox.position(from: currentRange.start,
offset: 200)
{
mainTextBox.selectedTextRange=mainTextBox.textRange(from: newPosition,
to: newPosition)
}
}
return false
}
}
previousSpaceTimestamp=now
}
else
{
previousSpaceTimestamp=nil
}
return true
}
Set the TextView Range Like this in Main Queue.
DispatchQueue.main.async {
mainTextBox.isEditable = true
mainTextBox.selectedRange = NSMakeRange(2, 0)
}

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

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

Resources