ios - 视图的布局不明确
问题描述
以编程方式,我正在尝试使用自动布局创建一个带有 5 个按钮的堆栈视图。当我运行项目时,它运行时没有显示任何错误,但没有显示按钮堆栈。
另一方面,在 Debug View Hierarchy 中,它显示“View has ambiguous layout”。我在这里缺少什么。
class TestView: UIView {
var stackView = UIStackView()
override init(frame: CGRect) {
super.init(frame: frame)
initComponents()
}
func initComponents() {
self.autoresizesSubviews = false
stackView.autoresizesSubviews = false
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.distribution = .equalSpacing
stackView.axis = .horizontal
stackView.alignment = .fill
stackView.contentMode = .scaleToFill
addSubview(stackView)
NSLayoutConstraint.activate([
stackView.leadingAnchor.constraint(equalTo: self.leadingAnchor),
stackView.trailingAnchor.constraint(equalTo: self.trailingAnchor),
stackView.topAnchor.constraint(equalTo: self.topAnchor),
stackView.bottomAnchor.constraint(equalTo: self.bottomAnchor),
])
for i in 0...4 {
let button = UIButton()
button.titleLabel?.text = "\(i)"
button.translatesAutoresizingMaskIntoConstraints = false
stackView.addSubview(button)
button.heightAnchor.constraint(equalTo: stackView.heightAnchor, multiplier: 1).isActive = true
button.widthAnchor.constraint(equalTo: button.heightAnchor, multiplier: 1).isActive = true
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}}
在 ViewController.swift 文件中
let frame = CGRect(x: 0, y: 0, width: 200, height: 30)
let test = TestView.init(frame: frame)
self.view.addSubview(test)
解决方案
我不得不改变一些事情来完成这项工作:
- 用于
button.setTitle(_:for:)
设置按钮的标题。 - 使用 为文本设置颜色
button.setTitleColor(_:for:)
。 - 为按钮设置背景颜色。
- 将按钮添加到
stackView
withstackView.addArrangedSubview(button)
。
此外,您可能希望将框架向下移动一点。它位于左上角,位于状态栏上方,位于 iPhone X 凹槽的后面。
for i in 0...4 {
let button = UIButton()
button.setTitle("\(i)", for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
// Set these colors to whatever you like
button.setTitleColor(.black, for: .normal)
button.backgroundColor = .red
stackView.addArrangedSubview(button)
button.heightAnchor.constraint(equalTo: stackView.heightAnchor, multiplier: 1).isActive = true
button.widthAnchor.constraint(equalTo: button.heightAnchor, multiplier: 1).isActive = true
}
推荐阅读
- c# - 我可以简单地进行冗长的速记字符串比较吗?
- php - 使用 PHP 仅删除特定字符之前的第一个单词
- python - 优化代码并避免python中的if语句
- google-cloud-platform - 在 Spanner 中拥有大量分片是否会产生成本?
- kubernetes - Prometheus 服务端点抓取服务的所有端口,而不仅仅是带注释的端口
- javascript - dataTable 不正确显示 ajax 数据
- azure - 使用 Java 自动转发 Azure 服务总线消息
- java - 如何使用 JPA 和 Hibernate 复制 INSERT/UPDATE/DELETE 语句
- python - Scapy/Kamene-如何提取数据包和帧信息?
- sapui5 - SAP UI5 BlockLayout - 如何设置可点击块?