1、UIButton 同時添加圖片和文字的時候,一般是圖片在左,文字在右,稍微加些間距,就可以滿足設計師們的要求;有些需求是文字在左,圖片在右,這個時候其實我們也只需要把UIbutton的方向改變一下就可以了:
UIView.userInterfaceLayoutDirection(for: .unspecified) = .rightToLeft
在XIB中就是UIButton下面的關於的 UIVIew的 semantic 改爲 force Right-to-Left
但是在Arabic時,會有問題,依然是right-to-left 這個時候,其實應該是 Left-to-Right ,所以我們需要對UIButton寫一個 extension
如下:
@IBInspectable
var autoSemanticContentBoth: Bool {
get {
return false
}
set {
if newValue {
if UIView.userInterfaceLayoutDirection(for: .unspecified) == .rightToLeft {
semanticContentAttribute = .forceLeftToRight
let leftInset = titleEdgeInsets.left
let rightInset = titleEdgeInsets.right
contentEdgeInsets = UIEdgeInsets(top: contentEdgeInsets.top, left: contentEdgeInsets.left, bottom: contentEdgeInsets.bottom, right: contentEdgeInsets.right+rightInset)
titleEdgeInsets = UIEdgeInsets(top: titleEdgeInsets.top, left: rightInset, bottom: titleEdgeInsets.bottom, right: leftInset)
} else if UIView.userInterfaceLayoutDirection(for: .unspecified) == .leftToRight {
semanticContentAttribute = .forceRightToLeft
}
if #available(iOS 13.0, *) {
} else {
layoutIfNeeded()
}
}
}
}
這個時候,在需要 文字在左,圖片在右 的UIButton,改變semantic 時,把分類中的autoSemanticContentBoth 屬性置爲on,就可以在Arabic時,也沒有問題了: