我想对NSDirectionalEdgeInsets
的{{3}}和UIButton
使用titleEdgeInsets
。有可能吗?
出于本地化的目的,在设置组件的插图时,可能需要iOS应用程序同时适应从左到右和从右到左两种语言。
Apple在iOS11上引入了contentEdgeInsets
,不幸的是,此方法仅应用于NSDirectionalEdgeInsets
之类的少数属性,弃用了directionalLayoutMargins
所用的UIEdgeInsets
。
NSDirectionalEdgeInsets
使用前导和跟踪修饰符代替左和右来遵循界面布局方向由其对应的UIEdgeInsets
使用。
为每个按钮/视图使用每个修改后的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)
}
答案 0 :(得分:1)
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 的userInterfaceLayoutDirection
this Stackoverflow answer。