将UIStackView添加为UIBarButtonItem的customview

时间:2019-01-20 21:45:57

标签: swift uikit uitoolbar

我尝试添加UIStackView作为UIBarButtonItem的自定义视图。

我首先尝试添加一个UIView作为自定义视图。

let list = UIView(frame: CGRect(x: 0, y: 0, width: 250, height: 44))
list.backgroundColor = .green
list.addSubview(stackView)
let item = UIBarButtonItem(customView: list )
topViewController?.setToolbarItems([item], animated: true)

这有效。我在UIToolBar中看到一个绿色的条。然后,我尝试将UIStackView添加到UIView

let red = UIView(frame: CGRect(x: 0, y: 0, width: 250, height: 30))
red.backgroundColor = .red
let stackView = UIStackView(frame: CGRect(origin: CGPoint.zero,
                                         size: CGSize(width: 250, height: 44)))
stackView.distribution = .fillEqually
stackView.axis = .horizontal
stackView.spacing = 5
stackView.alignment = .center
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.addArrangedSubview(red)
let list = UIView(frame: CGRect(x: 0, y: 0, width: 250, height: 44))
list.backgroundColor = .green
list.addSubview(stackView)
let item = UIBarButtonItem(customView: list )
topViewController?.setToolbarItems([item], animated: true)

但是,当我尝试这样做时,什么也没发生。 UIToolBar似乎是空的。我在做什么错了?

1 个答案:

答案 0 :(得分:1)

在这个答案中,我使用了两个UIViews

您必须给height constraints换两个UIViews

red.heightAnchor.constraint(equalToConstant: 30).isActive = true;
green.heightAnchor.constraint(equalToConstant: 30).isActive = true;

您必须对此行发表评论,

//stackView.translatesAutoresizingMaskIntoConstraints = false

完整代码:

    self.navigationController?.isToolbarHidden = false

    let red = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 30))
    red.backgroundColor = .red
    let green = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 30))
    green.backgroundColor = .green

    red.heightAnchor.constraint(equalToConstant: 30).isActive = true;
    green.heightAnchor.constraint(equalToConstant: 30).isActive = true;

    let stackView = UIStackView(frame: CGRect(x: 0, y: 0, width: 250, height: 30))
    stackView.distribution = .fillEqually
    stackView.axis = .horizontal
    stackView.spacing = 5
    stackView.alignment = .center
    //stackView.translatesAutoresizingMaskIntoConstraints = false
    stackView.addArrangedSubview(red)
    stackView.addArrangedSubview(green)

    let list = UIView(frame: CGRect(x: 0, y: 0, width: 250, height: 44))
    list.backgroundColor = .yellow
    list.addSubview(stackView)
    let item = UIBarButtonItem(customView: list )
    self.setToolbarItems([item], animated: true)

输出:

enter image description here