我正在以编程方式快速创建UIToolBar及其项:

    var items = [UIBarButtonItem]()
    let leftButton  = UIBarButtonItem(image: UIImage(named: "left"), style: .Plain, target: self, action: Selector("doneClickedMaButton"))
    let spacer      = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
    let rightButton = UIBarButtonItem(image: UIImage(named: "right"), style: .Plain, target: self, action: Selector("doneClickedRight"))
    let searchButton = UIBarButtonItem(barButtonSystemItem: .Search, target: self, action: Selector("doneClickedSearch"))
    items.append(leftButton)
    items.append(spacer)
    items.append(searchButton)
    items.append(spacer)
    items.append(rightButton)

var toolBar         = UIToolbar()
    toolBar.frame = CGRectMake(0, 0, self.view.frame.size.width, 50)
    toolBar.translatesAutoresizingMaskIntoConstraints = false
    toolBar.backgroundColor = UIColor.redColor()
    toolBar.items = items
    toolBar.sizeToFit()
    view.addSubview(toolBar)
    view.addConstraint(NSLayoutConstraint(item: toolBar, attribute: .Bottom, relatedBy: .Equal, toItem: view, attribute: .Bottom, multiplier: 1.0, constant: 0.0))


如果我不添加spacer项,则模拟器如下所示:

ios - 我的UIButtonBarItem不能与FlexibleSpace正确布局-LMLPHP

如果我确实将它们放入,则就像在此代码中这样说。我得到这个:

ios - 我的UIButtonBarItem不能与FlexibleSpace正确布局-LMLPHP

正如您在此处看到的那样,不仅图像现在从屏幕上向左掉落,而且不再按正确的顺序排列。

我以为.FlexibleSpace只会在项目之间添加动态间距。我在这里想念什么吗?在各种帖子中有人提到,可以在UIBarButtonItem中设置UILabel的宽度,这可以使.FlexibleSpace识别它。

最佳答案

问题是您没有足够的约束来满足自动布局引擎。您将工具栏固定在底部,但是宽度正在缩小,因此只能容纳按钮,但是您希望它是视图的宽度。尝试类似的东西:

var items = [UIBarButtonItem]()
    let leftButton  = UIBarButtonItem(image: UIImage(named: "left"), style: .Plain, target: self, action: Selector("doneClickedMaButton"))
    let spacer      = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
    let rightButton = UIBarButtonItem(image: UIImage(named: "right"), style: .Plain, target: self, action: Selector("doneClickedRight"))
    let searchButton = UIBarButtonItem(barButtonSystemItem: .Search, target: self, action: Selector("doneClickedSearch"))
    items.append(leftButton)
    items.append(spacer)
    items.append(searchButton)
    items.append(spacer)
    items.append(rightButton)

var toolBar         = UIToolbar()
    toolBar.frame = CGRectMake(0, 0, self.view.frame.size.width, 50)
    toolBar.translatesAutoresizingMaskIntoConstraints = false
    toolBar.backgroundColor = UIColor.redColor()
    toolBar.items = items
    toolBar.sizeToFit()
    view.addSubview(toolBar)
    toolBar.leadingAnchor.constraintEqualToAnchor(self.view.leadingAnchor).active = true
    toolBar.trailingAnchor.constraintEqualToAnchor(self.view.trailingAnchor).active = true
    toolBar.bottomAnchor.constraintEqualToAnchor(self.view.bottomAnchor).active = true

关于ios - 我的UIButtonBarItem不能与FlexibleSpace正确布局,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36270868/

10-12 14:49