首页 > 解决方案 > 添加 UIStackView 作为 UIBarButtonItem 的自定义视图

问题描述

我尝试将 a 添加UIStackView为 a 的自定义视图UIBarButtonItem

我首先尝试添加 aUIView作为自定义视图。

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. 然后我尝试UIStackViewUIView.

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似乎是空的。我究竟做错了什么?

标签: swiftuikituitoolbar

解决方案


在这个答案中,我使用了两个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)

输出:

在此处输入图像描述


推荐阅读