以编程方式创建 UIToolbar 后 UIBarButtonItems 不显示?

UIBarButtonItems not showing up after creating UIToolbar programmatically?

我 运行 遇到这个问题,我似乎无法在网上找到答案。基本上我想做的是以编程方式创建一个 UIToolbar 和一些 UIBarButtonItems

我所做的(详见下文)是创建 UIToolbar,然后将 UIToolbar 的项目设置为一个包含我想要的所有 UIBarButtonItems 的数组。

不幸的是,虽然UIToolbar出现了,UIBarButtonItems还没有出现

非常感谢任何关于为什么会发生这种情况的建议或解释!

class DrawViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        //create bar buttons
        let deleteBarButton = UIBarButtonItem(image: UIImage(named: "greyDelete"), style: .Plain, target: self, action: "deleteView:")
        let eraseBarButton = UIBarButtonItem(image: UIImage(named: "greyErase"), style: .Plain, target: self, action: "erase:")
        let resizeBarButton = UIBarButtonItem(image: UIImage(named: "greyResize"), style: .Plain, target: self, action: "resize:")
        let viewBarButton = UIBarButtonItem(image: UIImage(named: "greyView"), style: .Plain, target: self, action: "view:")
        let colorBarButton = UIBarButtonItem(image: UIImage(named: "greyColor"), style: .Plain, target: self, action: "color:")
        let drawBarButton = UIBarButtonItem(image: UIImage(named: "greyDraw"), style: .Plain, target: self, action: "draw:")
        let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: self, action: nil)

        //set up toolbar
        let toolbarItems = [deleteBarButton, flexibleSpace, eraseBarButton, 
                            flexibleSpace, resizeBarButton, flexibleSpace, 
                            viewBarButton, flexibleSpace, colorBarButton, 
                            flexibleSpace, drawBarButton]
        let toolbar = UIToolbar(frame: CGRectMake(0, view.bounds.height*0.93, view.bounds.width, view.bounds.height*0.7))
        toolbar.barTintColor = UIColor(patternImage: UIImage(named: "blueToolbar")!)
        toolbar.setItems(toolbarItems, animated: true)
        self.view.addSubview(toolbar)
    }

As you can see only the toolbar show up

And the image names (of the images used to create the UIBarButtons) are the same names as those in the Assets catalog

我认为问题出在您创建 UIToolbar 的奇怪方式。这里的这一行似乎很可疑:

let toolbar = UIToolbar(frame: CGRectMake(0, view.bounds.height*0.93, view.bounds.width, view.bounds.height*0.7))

为什么要将其设置为视图高度的 0.7 倍?

要解决此问题,请创建不带框架构造函数或为其框架添加 CGRectZero 的工具栏。然后使用sizeToFit()使其大小合适。

一个更简单的替代方法(如果可能)是使用 UINavigationController 并告诉它显示自己的工具栏。然后,您可以通过将视图控制器的 toolbarItems 属性 设置为您的数组来填充它,这一切都将在您根本不需要创建、定位或管理 UIToolbar 的情况下进行。