我有一个UIToolbar,其中包含多个不同字体大小的UIBarButtonItem。所有项目似乎都与某个基线对齐。根据工具栏的高度,特定的字体大小往往会出现在垂直中心。但其他项目偏心。如何将这些其他项目设置为显示在垂直中心?
注意:这些项目都是文本 - 没有图像。 许多其他回复非常陈旧和/或仅针对图像。大多数 obj.c 函数/方法都可以轻松转换为 Swift。
我使用以下方式放置元素:
func addLabel(_ text: String, textcolor: UIColor?, font: UIFont?, items: inout [UIBarButtonItem], verticalOffset: CGFloat) -> Int {
let item = UIBarButtonItem(title: text, style: UIBarButtonItem.Style.plain, target: nil, action: nil)
if font != nil {
item.setTitleTextAttributes([NSAttributedString.Key.font : font!], for: UIControl.State.normal)
}
if textcolor != nil {
item.tintColor = textcolor!
}
items.append(item)
return items.count-1
}
我试过了(这些都行不通):
- setTitleTextAttributes 和 .baselineOffset
- setTitlePositionAdjustment
- setBackgroundVerticalPositionAdjustment
let item = UIBarButtonItem(customView: itemView)
其中 itemView 是一个 UIView
也许是最后一个,我将 UILabel 包装在 View 中,然后将项目设置为 customView 可能有效,但对我来说它到处都是。我尝试将主要方法内容替换为:
let itemView = UIView(frame: CGRect(x: 0, y: verticalOffset, width: 0, height: 0))
let itemText = UILabel()
itemText.text = text
itemText.textColor = textcolor
itemText.font = font
itemText.sizeToFit()
itemView.translatesAutoresizingMaskIntoConstraints = false
let item = UIBarButtonItem(customView: itemView)
itemView.addSubview(itemText)
如何偏移工具栏上的某些项目?
最佳答案
好吧,我很接近。 我能够通过将每个标签包装在一个 View 中并将其设置为自定义 View 来解决这个问题。然后我添加了 itemText.center.y = self.center.y - verticalOffset
。但是标签将它们的垂直中心对齐到工具栏的底部 - 至少在我的。所以我将偏移量设置为工具栏高度的一半。它们出现在工具栏的垂直中心! (我还必须通过附加一些固定宽度的 UIBarButtonItem 来调整一些水平间距。)
之后,我在访问这些项目时遇到了一些困难 - 只是一小段时间。我设法通过使用 (items![abc].customView!.subviews[0] as! UILabel).text = "xyz"
更改了标签。 隐藏 项很容易:items![abc].customView?.alpha = 0
- 设置 1 表示显示。
关于swift - 如何在 Swift 中对 UIBarButtonItem 应用垂直对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55129412/