首页 > 解决方案 > Swift:工具栏项目出现在随机位置

问题描述

我目前正在实现一个带有自定义工具栏的应用程序。我将以编程方式添加的工具栏。我希望工具栏出现一个图像和一个文本,有些像这样:
图片下方有文字

不幸的是,我写的工具栏如下所示:
在此处输入图像描述

而且我真的不知道为什么它不起作用。
我写的代码如下:

  self.navigationController?.isToolbarHidden = false


    let customButton : UIButton = UIButton(type: .custom)
    customButton.setImage(UIImage(named: "Home"), for: .normal)
    customButton.imageView?.contentMode = .scaleAspectFit

    let customButton1 : UIButton = UIButton(type: .custom)
    customButton1.setImage(UIImage(named: "Account"), for: .normal)
    customButton1.imageView?.contentMode = .scaleAspectFit

    let customButton2 : UIButton = UIButton(type: .custom)
    customButton2.setImage((UIImage(named: "Ball")), for: .normal)
    customButton2.imageView?.contentMode = .scaleAspectFit


    customButton.imageEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
    customButton1.imageEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
    customButton2.imageEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)

    let customBarButtonItem = UIBarButtonItem(customView: customButton as UIView)
    let customBarButtonItem1 = UIBarButtonItem(customView: customButton1 as UIView)
    let customBarButtonItem2 = UIBarButtonItem(customView: customButton2 as UIView)

    var items = [UIBarButtonItem]()
    items.append( UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil))
    items.append( customBarButtonItem)
    items.append( UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil) )
    items.append( customBarButtonItem1)
    items.append( UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil) )
    items.append( customBarButtonItem2)



    self.toolbarItems = items

我知道代码看起来很糟糕,但我只想让它工作并且我发现没有解决方案对我有用。

另外,如果有人知道如何以编程方式构建工具栏的好教程,我会很感激这个链接。:)

标签: swifttoolbaritems

解决方案


这个自定义的 PagerController 可能会有所帮助,我已经使用它在视图顶部显示仅带有标题的选项卡,但是还有一个选项可以添加图标和 ViewController 的底部。

https://github.com/StepicOrg/stepik-ios/blob/master/PagerController.swift


推荐阅读