swift - 添加 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
. 然后我尝试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
似乎是空的。我究竟做错了什么?
解决方案
在这个答案中,我使用了两个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)
输出:
推荐阅读
- javascript - 如何从 js 中的 url 下载图像
- java - 将属性文件合并到 application.properties
- apache - 将子域指向另一台服务器上的另一个域
- java - 从另一个类返回整数数组列表在获取特定值时返回空指针异常
- python-3.x - ssl.SSLEOFError: EOF 发生违反协议 (_ssl.c:1129)
- r - dplyr unnest() 不适用于大逗号分隔的数据
- magento2 - Magento 后升级步骤:2.3 到 2.4
- javascript - 我想忽略动态值中的“\”
- python - 根据优先级 ID 更改看板视图中的文本颜色
- android - 如何将挂起函数的返回值存储到变量中?