使用swift将工具栏按钮移动到工具栏的左侧

时间:2018-06-07 15:30:31

标签: swift uibutton alignment uibarbuttonitem uitoolbar

我有一个放在底部(正确)的工具栏。问题是按钮(在UIBarButtonItem上)位于整个工具栏的中心。

如何将此按钮放在侧面,但仍然(垂直)居中于图像? 这是最好的保证金。

所以它看起来像

 --------------
|.    X
|.  label
 --------------

代码是:

    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)
    }
}

1 个答案:

答案 0 :(得分:0)

您是否正在寻找灵活的空格键按钮项目'或者'固定空格键按钮项目'?然后你可以在工具栏的左右两侧添加一点空间并定义它的大小。

看起来像这样:

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

spacer.width = 10