Right To Left - result0924/iosLearning GitHub Wiki

Add arabic to support RTL

Autolayout

如果使用的是Autolayout佈局,並且Autolayout下,
使用的是leading和trailing,
系統會自動幫助我們調整佈局,將其適配RTL。
但是如果使用的是left和right,系統是不會這麼做的。
所以為了適配佈局,我們需要將所有的left/right替換成leading和trailing。

ScrollView

extension UIScrollView {
    @objc func supportRightToLeft() {
        if UIApplication.shared.userInterfaceLayoutDirection == .leftToRight {
            let newTransform = CGAffineTransform(scaleX: -1, y: 1)
            transform = newTransform
            subviews.forEach { subView in
                subView.transform = newTransform
            }
        }
    }
}

UIButton

.contentHorizontalAlignment
  - left -> leading
  - right -> trailing
.imageEdgeInsets / .titleEdgeInsets
  - 原本設左邊的padding要改為右邊的
extension UIButton {

    /// Sets image insets with conformance to user interface direction
    ///
    /// - Parameters:
    ///     - insets: Image insets
    func setImageEdgeInsets(_ insets: UIEdgeInsets) {
        if UIApplication.shared.userInterfaceLayoutDirection == .leftToRight {
            imageEdgeInsets = insets
        } else {
            self.contentEdgeInsets = UIEdgeInsets(top: insets.top, left: insets.right, bottom: insets.bottom, right: insets.left)
        }
    }

    /// Sets title insets with conformance to user interface direction
    ///
    /// - Parameters:
    ///     - insets: Title insets
    func setTitleEdgeInsets(_ insets: UIEdgeInsets) {
        if UIApplication.shared.userInterfaceLayoutDirection == .leftToRight {
            titleEdgeInsets = insets
        } else {
            titleEdgeInsets = UIEdgeInsets(top: insets.top, left: insets.right, bottom: insets.bottom, right: insets.left)
        }
    }

}

UITextField

extension UITextField {
    open override func awakeFromNib() {
        super.awakeFromNib()

        if textAlignment == .natural {
            (UIApplication.shared.userInterfaceLayoutDirection == .leftToRight) ? (textAlignment = .right) : (textAlignment = .left)
        }
    }
}

String

extension String {
    func forceUnicodeLTR() -> String {
        return "\u{200E}\(self)\u{202c}"
    }
    
    func forceUnicodeRTL() -> String {
        return "\u{200F}\(self)\u{202c}"
    }
}

UIImageView

  • can use imageFlippedForRightToLeftLayoutDirection
rightArrow.image = rightArrow.image?.imageFlippedForRightToLeftLayoutDirection()

Refer