ios - prepareForInterfaceBuilder 中的约束?
问题描述
我不是 的忠实粉丝@IBDesignable
,但在玩弄它时,我发现如果在 中添加子视图,则会添加子视图prepareForInterfaceBuilder
,但不会遵守您应用到它的约束。
这是已知的限制prepareForInterfaceBuilder
吗?这是有道理的;我想这种方法应该仅限于做一些事情,比如给标签一些虚拟文本。
解决方案
确保在添加子视图时将prepareForInterfaceBuilder
其translatesAutoresizingMaskIntoConstraints
属性设置为false
是否要对其使用约束并使其在 Interface Builder 中正确显示。如:
@IBDesignable class View: UIView {
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
let subview = UIView()
// Make sure to set this to false!
subview.translatesAutoresizingMaskIntoConstraints = false
// Just setting the background color so it can be seen in IB.
subview.backgroundColor = .blue
// Must add it as a subview before activating any constraints.
addSubview(subview)
// Adding some example constraints with some padding to make sure they're behaving properly.
NSLayoutConstraint.activate(
[subview.topAnchor.constraint(equalTo: topAnchor, constant: 20),
subview.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 20),
subview.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -20),
subview.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -20)]
)
}
}
这是一个容易犯的错误,因为 Xcode(在编写此答案时为 10.3)不会向您提供有关IBDesignable
渲染期间布局引擎发生的情况的任何反馈(没有控制台日志消息,Interface Builder 中没有错误,并且 Report Navigator 中没有任何内容)。
推荐阅读
- python - 当 groupie 后跟 value_counts() 时如何计算 pandas.Series 范围
- apache-kafka - 错误:无法找到或加载主类 Folder.confluent-5.5.1-2.12.tar.confluent-5.5.1-2.12.confluent-5.5.1.logs
- javascript - 如何正确保存我的登录详细信息和重定向页面?
- python - jinja2.exceptions.UndefinedError
- php - 如何将带有数据的数据库导入新的 Laravel 数据库?
- java - 如何在 JNA 中正确映射 CERT_SELECT_STRUCT
- python - 使用pyarrow读取保存为镶木地板的DataFrame,将文件名保存在列中
- c++ - c++中makefile在清理时出错,找不到文件
- c - 在函数中分配内存,然后在外部使用
- reactjs - 我无法启动 React 项目,因为 node_models 文件丢失但它们存在