我无法将紧排空间添加到标签栏属性文本中。 有问题的 UITabBar 是一个自定义的 tabBar,您可以在下面找到代码。
我正在使用“属性键”字典向项目标题添加属性,但我遇到了紧排空间问题。
class ProfileTabBar: UITabBar {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setStyle()
}
required override init(frame: CGRect) {
super.init(frame: frame)
self.setStyle()
}
func setStyle() {
self.tintColor = Style.shared.primary1
// Disable the default border
self.layer.borderWidth = 0.0
self.clipsToBounds = true
// Create a new bottom border
let bottomLine = CALayer()
let screenWidth = UIScreen.main.bounds.width
//let viewForFrame = self.superview ?? self
//let screenWidth = viewForFrame.bounds.width
bottomLine.frame = CGRect(x: 0.0, y: self.frame.height - 1, width: screenWidth, height: 2.0)
bottomLine.backgroundColor = UIColor(red: 235.0/255, green: 235.0/255, blue: 235.0/255, alpha: 1.0).cgColor
self.layer.addSublayer(bottomLine)
// Get the size of a single item
let markerSize = CGSize(width: screenWidth/CGFloat(self.items!.count), height: self.frame.height)
// Create the selection indicator
self.selectionIndicatorImage = UIImage().createSelectionIndicator(color: self.tintColor, size: markerSize , lineWidth: 3.0)
// Customizing the items
if let items = self.items {
for item in items {
item.titlePositionAdjustment = UIOffset(horizontal: 0, vertical: -15)
let attributes: [NSAttributedStringKey : Any] = [
NSAttributedStringKey.font: UIFont(name: Style.shared.fontBold.fontName, size: 14) as Any,
NSAttributedStringKey.kern: NSNumber(value: 1.0)
]
item.setTitleTextAttributes(attributes, for: .normal)
}
}
}
除了紧排外,所有属性都有效。我做错了什么?
最佳答案
这个问题很老了,还有一个更老的答案 here 。 UITabBarItem
外观似乎忽略了 NSAttributedString.Key.kern
。这给我们留下了一些选择。
子类
UITabBarItem
这并不容易,因为UITabBarItem
继承自UIBarItem
,它是一个NSObject
不是UIView
。子类
UITabBar
这可以完成,但只需要一些紧排就需要大量工作。您必须使用UIButton
而不是UITabBarItem
以便应用 kern。您可以在标题中使用 unicode 字符添加间距。这非常简单,只需几行代码就可以实现您正在寻找的间距。
U+0020
1/4 em
U+2004
1/3 em
U+2005
1/4 em
U+2006
1/6 em
U+2008
句号“.”的宽度
U+2009
1/5 em(有时是 1/6 em)
您可以在 Swift 中的 String
中使用 unicode 字符,例如 "\u{2006}"
。这意味着我们可以在 tabBarItem 标题中的所有字符之间插入一个小空格。像这样:
extension String {
var withOneSixthEmSpacing: String {
let letters = Array(self)
return letters.map { String($0) + "\u{2006}" }.joined()
}
将其用于我们的 tabBarItems:
self.navigationController.tabBarItem = UITabBarItem(
title: "Home".withOneSixthEmSpacing,
image: homeImage,
selectedImage: homeSelectedImage
)
代替:
关于iOS swift : add kern space in the tab bar text,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50676585/