How to center align text in UITextView?
Interesting question: I would try to count the lines in the textView and cut the last, than try to put the cut text on a new label below the textView ...;)
after i ask how to do it i added the following:
print(self.testLabel.frame.width)
self.testLabel.text = "Hello World"
self.testLabel.sizeToFit()
print(self.testLabel.frame.width)
This is the starting point from which you can work. Create a label and set the width to zero. Insert text and set sizeToFit (). Now you can get the length of the label. Is it enough for your idea that it will have more lines ... (Divisor is your length - not checked, may need an offset)
The idea is to subtract if your lines are more than one and lines at the beginning of your calculation to get the last word and put it at the beginning of the temp line. If it does return, you get your substring for the last line.
I was curious and started with this:
@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)
}
}
interesting result:
total 1499.5
lines 7
Optional("civiuda.")
Of course, you should spend more time calculating because of the free space at the end of the line ...
source to share
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
source to share