【问题标题】:Add UIStackView as a customview of a UIBarButtonItem添加 UIStackView 作为 UIBarButtonItem 的自定义视图
【发布时间】:2019-01-20 21:45:56
【问题描述】:

我尝试添加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 似乎是空的。我做错了什么?

【问题讨论】:

  • 你为什么不使用多个项目而不是尝试将它们全部放在堆栈视图中?
  • @LeoDabus 用于它们之间的间距。我找不到改变UIToolBar 中各个项目之间间距的好方法,所以我认为这是第二好的解决方案。
  • 如果需要,您可以使用灵活宽度的项目
  • @LeoDabus 好吧,我需要的空间比项目之间的默认宽度要少。所以这就是为什么。
  • 没有运行您的代码,但对我来说似乎没问题,顺便说一句,您可以查看约束是否有效/无效

标签: swift uikit uitoolbar


【解决方案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)

输出:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-11
    • 2016-02-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多