ios - 在 UIStackView 中自动配置组件(以编程方式)
问题描述
你好。如您所见,组件在 a 中重叠,UIStackView
我正在为此苦苦挣扎。
以下是一些代码片段
class BottomSheetController: UIViewController {
lazy var headerLabel: UILabel = {
let label = UILabel()
label.text = "Workout"
return label
}()
lazy var header: UIView = {
let uiView = UIView()
return uiView
}()
lazy var workoutInput: UITextField = {
let textField = UITextField()
textField.placeholder = "Find or add option"
textField.sizeToFit()
textField.clipsToBounds = true
textField.backgroundColor = UIColor(red: 65 / 255.0, green: 65 / 255.0, blue: 65 / 255.0, alpha: 0.4)
textField.layer.cornerRadius = 5
textField.setImage(image: UIImage(named: "search_black")!)
textField.setClearTextButton()
return textField
}()
lazy var tagsView: UIScrollView = {
let scrollView = UIScrollView()
scrollView.backgroundColor = .red
return scrollView
}()
lazy var containerStackView: UIStackView = {
let stackView = UIStackView(arrangedSubviews: [header, workoutInput, tagsView])
stackView.clipsToBounds = true
stackView.axis = .vertical
stackView.backgroundColor = .systemGray2
return stackView
}()
// ...
private func setConstraint() {
header.addSubview(headerLabel)
header.addSubview(doneButton)
containerStackView.snp.makeConstraints { make in
make.top.left.right.bottom.equalToSuperview().inset(20)
}
headerLabel.snp.makeConstraints { make in
make.top.centerX.equalToSuperview()
}
doneButton.snp.makeConstraints { make in
make.top.right.equalToSuperview()
}
workoutInput.snp.makeConstraints {make in
make.height.equalTo(40)
}
}
}
我的问题可能是,header
视图没有恒定的高度值
但我不想设置要header
查看的幻数。而是分配与子视图对应的值 ( workoutInput
)
- 有没有花哨的方法来调整高度?
- 如何防止组件重叠?
解决方案
您需要添加足够的约束以满足自动布局要求。
AUIView
没有内在大小......所以你header
最终的高度为零。
进行一些更改以控制该视图的高度:
private func setConstraint() {
header.addSubview(headerLabel)
header.addSubview(doneButton)
containerStackView.snp.makeConstraints { make in
// constrain to safe area, not to superView
make.top.left.right.bottom.equalTo(view.safeAreaLayoutGuide).inset(20)
}
headerLabel.snp.makeConstraints { make in
make.top.centerX.equalToSuperview()
// constrain label bottom to superview
make.bottom.equalToSuperview()
}
doneButton.snp.makeConstraints { make in
make.top.right.equalToSuperview()
// constrain button bottom to superview
make.bottom.equalToSuperview()
}
workoutInput.snp.makeConstraints {make in
make.height.equalTo(40)
}
}
附带说明一下,如果您为 UI 元素提供对比背景色,您会发现调试布局会更容易,例如:
header.backgroundColor = .systemTeal
headerLabel.backgroundColor = .yellow
doneButton.backgroundColor = .green
通过这些更改,您应该看到以下内容:
推荐阅读
- java - 多个 Java 类实例同时读取同一个 Map 是否存在线程安全问题?
- xml - 更新 XML 中 if 条件的值时出错
- amazon-eks - 我们可以添加 EKS windows Worker 节点吗?
- python - 在 Bitnami Odoo Stack 中升级 pip
- javascript - Google Bucket - 获取特定文件
- apache-dolphinscheduler - 监控中心Zookeeper管理界面显示异常
- node.js - 如何从 URL 获取文件作为 Buffer 对象?
- c++ - 如何解析包含具有增强精神的嵌入式引号的引号字符串
- javascript - 将 Click 事件侦听器添加到 Angular 中动态插入的元素
- node.js - 是否可以在同一个端口中运行 Node 和 React?