swift - 快速将工具栏按钮移到工具栏的左侧
问题描述
我有一个放置在底部的工具栏(正确)。问题是按钮(在 UIBarButtonItem 上)位于整个工具栏的中心。
如何将此按钮放置在侧面,但仍(垂直)与图像居中? 最好有余量。
所以它看起来像
-------------- |。X |。标签 --------------
代码是:
let customButton: UIButton = UIButton(type: .custom)
customButton.setImage(UIImage(named: "start"), for: .normal)
customButton.setTitle("Start", for: .normal)
customButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: 12)
customButton.setTitleColor(UIColor.white, for: .normal)
customButton.sizeToFit()
customButton.centerLabelVerticallyWithPadding(spacing: 5)
customButton.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(startButtonAction(_:))))
iconBar.items = [UIBarButtonItem(customView: customButton)]
其中iconBar
- 工具栏定义为:
let iconBar: UIToolbar =
{
let view = UIToolbar()
view.translatesAutoresizingMaskIntoConstraints = false
view.barTintColor = UIColor.black
return view
}()
此外,我正在使用扩展来使 UIButton 居中,然后我可以在其上方添加一个图像(也居中)。这是扩展名:
extension UIButton
{
func centerLabelVerticallyWithPadding(spacing:CGFloat)
{
// update positioning of image and title
let imageSize = self.imageView!.frame.size
self.titleEdgeInsets = UIEdgeInsets(top:0,
left:-imageSize.width,
bottom:-(imageSize.height + spacing),
right:0)
let titleSize = self.titleLabel!.frame.size
self.imageEdgeInsets = UIEdgeInsets(top:-(titleSize.height + spacing),
left:0,
bottom: 0,
right:-titleSize.width)
// reset contentInset, so intrinsicContentSize() is still accurate
let trueContentSize = self.titleLabel!.frame.union(self.imageView!.frame).size
let oldContentSize = self.intrinsicContentSize
let heightDelta = trueContentSize.height - oldContentSize.height
let widthDelta = trueContentSize.width - oldContentSize.width
self.contentEdgeInsets = UIEdgeInsets(top:heightDelta/2.0,
left:widthDelta/2.0,
bottom:heightDelta/2.0,
right:widthDelta/2.0)
}
}
解决方案
您在寻找“灵活的空格键按钮项”还是“固定的空格键按钮项”?然后您可以在工具栏内的左右添加一点空间并定义它的大小。
它看起来像这样:
let spacer = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
spacer.width = 10
推荐阅读
- spring - 具有动态目的地的春季云流多接收器
- android - 在 Android 10+ 上从外部存储(包括下载文件夹)获取所有文件
- android - 如果在两种情况下都启用数据绑定,则 binding.name.text && name.text 有什么区别
- plot - Seaborn 双胞胎情节未按预期工作
- c# - 使用 .NET 中的数据绑定项从集合的 id 设置组合框值
- reactjs - 在函数中的 onSubmit 之后添加警报
- django - Django 订阅者功能
- c# - 将cURL请求转换为asp.net c#
- excel - Excel - 有没有办法告诉一个单元格使用基于另一个单元格的第一个字母的某个功能?
- r - 拆分面板回归在 R 中得到一个独特的结果