我想将
NSDirectionalEdgeInsets
用于UIButton
的contentEdgeInsets
和titleEdgeInsets
。这可能吗?
出于本地化目的,iOS 应用程序在设置组件的插图时可能需要适应从左到右和从右到左的语言。
NSDirectionalEdgeInsets
,不幸的是,这仅应用于少数属性,例如 directionalLayoutMargins
,弃用了用于 UIEdgeInsets
的 layoutMargins
。
NSDirectionalEdgeInsets
使用 leading 和 trailing 修饰符来尊重界面布局方向,而不是其对应的 UIEdgeInsets
使用的 left 和 right。
对每个修改过的
UIEdgeInsets
属性的每个按钮/视图使用以下代码非常麻烦,并且在进行更改时容易出错:
let isRTL: UIUserInterfaceLayoutDirection = // logic to determine language direction
if isRTL == .leftToRight {
nextButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0)
} else {
nextButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 10)
}
import UIKit
extension UIView {
// Returns `UIEdgeInsets` set using `leading` and `trailing` modifiers adaptive to the language direction
func getDirectionalUIEdgeInsets(top: CGFloat, leading: CGFloat, bottom: CGFloat, trailing: CGFloat) -> UIEdgeInsets {
// NOTE: this wil be deprecated when Apple use `NSDirectioanlEdgeInsets` (https://developer.apple.com/documentation/uikit/nsdirectionaledgeinsets) for your insets property instead of `UIEdgeInsets`
if self.userInterfaceLayoutDirection == .leftToRight {
return UIEdgeInsets(top: top, left: leading, bottom: bottom, right: trailing)
} else {
return UIEdgeInsets(top: top, left: trailing, bottom: bottom, right: leading)
}
}
/// Returns text and UI direction based on current view settings
var userInterfaceLayoutDirection: UIUserInterfaceLayoutDirection
{
if #available(iOS 9.0, *) {
return UIView.userInterfaceLayoutDirection(for: self.semanticContentAttribute)
} else {
return UIApplication.shared.userInterfaceLayoutDirection
}
}
}
nextButton.contentEdgeInsets = nextButton.getDirectionalUIEdgeInsets(top: 0, leading: 10, bottom: 0, trailing: 0)
我在 Stackoverflow 上寻找答案,但一无所获。因此我分享我的答案。
感谢 David Rysanek 的 Stackoverflow 回答 提供了
userInterfaceLayoutDirection
扩展。