Reputation: 27235
I have implemented Language Localization in my iOS App. So, now user can set the Arabic Language in my iPad Application.
I am getting the localized string response from the server and now I want to set this localized string to my UILabel
in Right To Left format with Right Alignment.
Update :
My server response is already in RTL format. Now, I just wanted to set the text alignment to right when I have Arabic text in my UILabel
.
Right now I have to write code to set the alignment of UILabel
based on the language.
So, I just want to know if there is any property available for UILabel
by setting which I can make the text of UILabel
Right Aligned in case of Arabic Language.
Upvotes: 8
Views: 11696
Reputation: 199
For anyone wanting an example using the NaturalLanguage library (NSLinguisticTagger is deprecated). This builds on @jaspreetkour's answer, and also works with attributed text.
extension UILabel {
func decideTextDirection () {
let recognizer = NLLanguageRecognizer()
var txt = self.text ?? ""
if txt.isEmpty {
// check attributed text
txt = self.attributedText?.string ?? ""
}
if !txt.isEmpty {
recognizer.processString(txt)
if let language = recognizer.dominantLanguage {
switch language {
case .arabic:
self.textAlignment = .right
default:
self.textAlignment = .left
}
}
}
}
}
Upvotes: 0
Reputation: 837
For Swift3 //MARK: UILabel extension
extension UILabel {
func decideTextDirection () {
let tagScheme = [NSLinguisticTagSchemeLanguage]
let tagger = NSLinguisticTagger(tagSchemes: tagScheme, options: 0)
tagger.string = self.text
let lang = tagger.tag(at: 0, scheme: NSLinguisticTagSchemeLanguage,
tokenRange: nil, sentenceRange: nil)
if lang?.range(of:"ar") != nil {
self.textAlignment = NSTextAlignment.right
} else {
self.textAlignment = NSTextAlignment.left
}
}
to use this add following with your label :
detailLabel.text = details[0]
detailLabel.decideTextDirection()
Upvotes: 6
Reputation: 6530
Make your text label the entire width of the view. Then the text will right align from the right side of the screen.
Upvotes: 1
Reputation: 1398
have you try this.
[[self label] setTextAlignment:NSTextAlignmentNatural];
AutoLayout + RTL + UILabel text alignment
Hope this will solve your problem.
Upvotes: 4
Reputation: 88
Display the text normally as you do in english if you are getting arabic text from server no need to align it. Just right align the text.
Upvotes: 2