为什么(阿拉伯语和英语)文本无法右对齐?

6

这是我使用的字符串:

情况1

    var word1 = "عبد الله"
    var word2 = "restaurant"
    label.text = " \(word1) found your review on \(word2) useful."

结果:

a

案例2

    var word1 = "عبد الله"
    var word2 = "restaurant"
    label.text = "note: \(word1) found your review on \(word2) useful."

结果:

b

问题

那么,如何使第一个单词向右包装?如果第一个单词是阿拉伯语,它会被包装到左边,但如果第一个单词是英语,则情况是可以预料的,那么如何在第一个单词在左侧时显示word1?

我尝试了以下两种方法:

label.textAlignment = NSTextAlignment.Left

并且

label.textAlignment = NSTextAlignment.Natural

没有任何运气。

2个回答

10

Unicode有两个标记字符(从左到右:0x200E,从右到左:0x200F)。它们是不可见的,但可以控制文本方向。我只需要添加这个\u{200E}来强制换行方向。

 \u{200E} \(word1) found your review on \(word2) useful.

编辑: 请参见此处的完整教程,以获取更多信息。


1
最佳实践是在“从右到左覆盖”序列(即以\u{200E}开头的字符序列)末尾添加“弹出方向格式化”字符(即\u{200C})。您可以在此处阅读有关方向格式化字符的更多信息:http://www.unicode.org/reports/tr9/。 - Adil Hussain

2
作为UIView的子类,UILabel有一个名为semanticContentAttribute的变量,您可以将其设置为.foreRightToLeft,也可以通过属性检查器中的语义弹出菜单从nib inspector进行设置。

此外,您可以查询effectiveUserInterfaceLayoutDirection属性来调试其状态。

请参阅此处了解更多信息。

现在,如果您需要在一个标签中使用两种对齐方式,这将是棘手的。要么将两个标签组合到一个UIView容器中,要么查看是否可以为NSMutableAttributedString的一部分设置这些值,然后将其提供给UILabel

您尝试设置的textAlignment属性将为段落对齐提供与MS-Word相同的效果,但不会翻转语言的阅读方向。

祝编码愉快!

编辑:这是使用属性字符串建议的示例,尽管将阿拉伯语设置更改为从右到左,但它会将其放置在字符串底部...也许需要以不同的方式组合标志?

override func viewDidLoad() {
    super.viewDidLoad()
    let label = UILabel()

    let myMutableString = NSMutableAttributedString()

    //right-to-left
    let multipleAttributes: [String : AnyObject] = [
        NSForegroundColorAttributeName: UIColor.orangeColor(),
        NSBackgroundColorAttributeName: UIColor.blueColor(),
        NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleDouble.rawValue,
        NSWritingDirectionAttributeName : [NSWritingDirection.LeftToRight.rawValue ]
    ]

    let myAttrString = NSAttributedString(string: "عبد الله", attributes: multipleAttributes)

    myMutableString.appendAttributedString(myAttrString)

    //some-text

    let someText = NSAttributedString(string: " finds ", attributes: nil)

    myMutableString.appendAttributedString(someText)

    //left-to-right
    let multipleAttributes2: [String : AnyObject] = [
        NSForegroundColorAttributeName: UIColor.blueColor(),
        NSBackgroundColorAttributeName: UIColor.yellowColor(),
        NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleDouble.rawValue,
        NSWritingDirectionAttributeName : [NSWritingDirection.LeftToRight.rawValue | NSTextWritingDirection.Embedding.rawValue]
    ]

    let myAttrString2 = NSAttributedString(string: "restaurant", attributes: multipleAttributes2)

    myMutableString.appendAttributedString(myAttrString2)

    label.attributedText = myMutableString

    self.view.addSubview(label)
    label.sizeToFit()
    label.center = self.view.center

}

最终我找到了方法,只需要看一下我添加的答案就行了。 - DeyaEldeen
太棒了!我正在设置一个示例,但是不得不去开会。我会看看这是否也适用于我的方法。 - jugutier
@DeyaEldeen 这就是我想要的,尽管我还没有让它对我起作用。 - jugutier

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接