5

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?

Ahmad F
  • 30,560
  • 17
  • 97
  • 143

3 Answers3

0

just make it .center i know what exactly you're looking for cause i've been there before, only you can make it .center

Sameh Salama
  • 765
  • 1
  • 7
  • 17
0

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.") 

I used this basic text

Of course you should spent more time in the calculation because of the free space at the end of a line...

Johannes Knust
  • 891
  • 1
  • 11
  • 18
0

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
Masoud Roosta
  • 455
  • 9
  • 19