I'm having problems with UILabels that use NSAttributedStrings
with NSParagraphStyle
when I use UISemanticContentAttributeForceRightToLeft
.
I have a demo app with just 2 labels on the UI.
They have leading and trailing constraints.
I'm making the app Right to Left in the AppDelegate with
UIView.appearance().semanticContentAttribute = .forceRightToLeft
And I'm just configuring the labels with the following code
let labelAText = "Foo"
let mutAttrString = NSMutableAttributedString(string: labelAText)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .natural
paragraphStyle.baseWritingDirection = .natural
mutAttrString.setAttributes([NSAttributedStringKey.paragraphStyle: paragraphStyle.copy()], range: NSMakeRange(0, labelAText.count))
labelA.attributedText = mutAttrString
labelB.text = "Bar"
Which results in this:
[
The labelB (Bar)
is working as expected, but the labelA (Foo)
isn't. And if I just remove the NSParagraphStyle
it starts working. Mind that I'm not even changing anything on it, but just by using it it's messing up with the alignment.
Any thoughts on what might be causing this?
NSMutableParagraphStyle has a property baseWritingDirection (enum NSWritingDirection ). Set it to rightToLeft
Try this
paragraphStyle.baseWritingDirection = NSWritingDirection.rightToLeft
Edit :(May this help you)
If the value of property (baseWritingDirection) is NSWritingDirectionNaturalDirection, the receiver resolves the writing direction to either NSWritingDirectionLeftToRight or NSWritingDirectionRightToLeft, depending on the direction for the user's language preference setting.
class func defaultWritingDirection(forLanguage languageName: String?) -> NSWritingDirection
languageName : The language specified in ISO language region format. Can be nil to return a default writing direction derived from the user's defaults database.
Solution using languageName = "ar"
@IBOutlet weak var labelA: UILabel!
let labelAText = "Foo"
let mutAttrString = NSMutableAttributedString(string: "Foo")
let paragraphStyle = NSMutableParagraphStyle()
//paragraphStyle.alignment = .natural
paragraphStyle.baseWritingDirection = NSParagraphStyle.defaultWritingDirection(forLanguage: "ar")
mutAttrString.setAttributes([NSAttributedStringKey.paragraphStyle: paragraphStyle], range: NSMakeRange(0, labelAText.count))
labelA.attributedText = mutAttrString
Here is list of languages: Codes for the Representation of Names of Languages
Note: Use ISO 639-1
code for language. Direction of label text depends upon natural direction of language.
Here is result:
This Apple document will help you - Supporting Right-to-Left Languages
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.