swift how to get UILabel align to top left - ios

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.

Related

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.

How to center justify text in UITextView?

I have an Arabic (right to left) text in textView, when I set myTextView.alignment = .justify, the last line in text go to the left side. How can I set center justify for textView or how can move last line to the center?
just make it .center
i know what exactly you're looking for cause i've been there before, only you can make it .center
Interesting question, I would try to count the lines in the textView and cut the last one than I would try to put the cut text in a new label below the textView ... ;)
after asking how I would do this I added this:
print(self.testLabel.frame.width)
self.testLabel.text = "Hello World"
self.testLabel.sizeToFit()
print(self.testLabel.frame.width)
This is a starting point you can work with. Create a label and set the width to zero. Insert your text and set sizeToFit(). Now you are able to get the length of the label. Is it to long for your view it will have more lines... (The divider is your length - not tested, maybe an offset is needed too)
The idea is now to subtract as long as your lines are more than one and the lines are the same amount at the beginning of your calculation to get the last word and put it at the beginning of a temp string.
If this returns you get your substring for the last line.
I was interested and started with this one:
#IBOutlet weak var textBox: UITextView!
#IBOutlet weak var testLabel: UILabel!
override func viewWillAppear(_ animated: Bool) {
print(self.testLabel.frame.width)
self.testLabel.text = self.textBox.text
self.testLabel.sizeToFit()
print("total \(self.testLabel.frame.width)")
let basicAmount = Int(self.testLabel.frame.width / self.textBox.frame.width) + 1
print("lines \(basicAmount)")
var lastLine: String = ""
while basicAmount == Int(self.testLabel.frame.width / self.textBox.frame.width) + 1 {
var arr = self.textBox.text.components(separatedBy: " ")
lastLine = "\(arr.last) \(lastLine)"
arr.removeLast()
self.textBox.text = arr.joined(separator: " ")
self.testLabel.text = self.textBox.text
self.testLabel.sizeToFit()
print(lastLine)
}
}
the interesting output is:
total 1499.5
lines 7
Optional("civiuda.")
Of course you should spent more time in the calculation because of the free space at the end of a line...
use this
self.textView.textAlignment = .justified //set text alignment center and justified
self.textView.makeTextWritingDirectionRightToLeft(true)//if you want set writing direction right to left
self.textView.makeTextWritingDirectionLeftToRight(true)//if you want set writing direction left to right

UINavigationItem title truncation

I have text that is built from two Strings:
A(B)
I want to use both strings as the title for the UINavigationItem but in case of truncation I want only A to be truncated and not B.
Example:
The title I want is "The quick brown fox jumps (over the lazy dog)".
The screen size is too small so the title truncates and it is now "The quick brown fox jumps (over...".
What I want it to be is: "The quick br... (over the lazy dog)"
How can I do that?
First check number of characters navigation bar allowing as title without truncating. Next, before setting title check whether the total string length is less than those number of characters or not. Now based on condition set either combined string or B only.
Since xcode won't be able to detect in which part of your title you want to stop and which part you want to start again, you need to do it yourself.
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "Heal the world make it a better place for you and for me and the entire human race"
setNavTitle(title: self.navigationItem.title!)
}
func setNavTitle(title: String)
{
//get the last 10 characters of your title, change the number to your need
let last10 = title.substring(from:title.index(title.endIndex, offsetBy: -14))
//get the first 10 characters of your title, change the number to your need
let first10 = title.substring(to: title.index(title.startIndex, offsetBy: 14))
//concatenate the strings
let title = first10 + " ... " + last10
self.navigationItem.title = title
}

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.

UITextView top of the text is shown half when pressed on new line, rest is clipped

Check out the gif below, as you see the textview is normal. When I press the return button the top text gets clipped, when I enter a letter or press return again its fixed. After that the next return also clips the text. There is also unnecessary space created at the bottom.
Here is the code I use under UITextViewDelegate:
func textViewDidChange(textView: UITextView) {
textView.h = textView.contentHeight
contentTextContainer.h = textView.contentHeight + 20 //Unnecessary but..
}

Resources