【问题标题】:UIBarButtonItems not showing up after creating UIToolbar programmatically?以编程方式创建 UIToolbar 后 UIBarButtonItems 未显示?
【发布时间】:2015-12-17 00:29:11
【问题描述】:

我遇到了这个问题,我似乎无法在网上找到答案。基本上我想做的是以编程方式创建一个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

【问题讨论】:

    标签: ios swift uibarbuttonitem uitoolbar


    【解决方案1】:

    我想问题在于您创建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

    【讨论】:

    • 哇,现在我可以看到我所有的按钮了!谢谢!但是现在工具栏显示在屏幕顶部而不是底部。你知道我怎样才能把工具栏放在底部吗?
    • 没关系,我想通了!但是谢谢你的帮助!你为我节省了很多时间!
    • 我很高兴听到它奏效了。您能否将我的答案标记为正确,以便其他人也可以受益?谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-21
    • 1970-01-01
    • 2016-11-04
    相关资源
    最近更新 更多