首页 > 解决方案 > 快速将工具栏按钮移到工具栏的左侧

问题描述

我有一个放置在底部的工具栏(正确)。问题是按钮(在 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)
    }
}

标签: swiftuibuttonalignmentuibarbuttonitemuitoolbar

解决方案


您在寻找“灵活的空格键按钮项”还是“固定的空格键按钮项”?然后您可以在工具栏内的左右添加一点空间并定义它的大小。

它看起来像这样:

let spacer = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)

spacer.width = 10

推荐阅读