如何调试这个错误?似乎没有额外的错误描述。
失败的代码:
import UIKit
import PlaygroundSupport
let containerView = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
containerView.backgroundColor = UIColor.white
let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
containerView.addSubview(stackView)
stackView.addConstraint(.init(item: stackView, attribute: .top, relatedBy: .equal, toItem: containerView, attribute: .top, multiplier: 1, constant: 0))
stackView.addConstraint(.init(item: stackView, attribute: .leading, relatedBy: .equal, toItem: containerView, attribute: .leading, multiplier: 1, constant: 0))
PlaygroundPage.current.liveView = containerView // error: Execution was interrupted, reason: signal SIGABRT.
完整错误:
error: Execution was interrupted, reason: signal SIGABRT. The process has been left at the point where it was interrupted, use "thread return -x" to return to the state before expression evaluation.
完整控制台日志:
libc++abi.dylib: terminating with uncaught exception of type NSException
最佳答案
问题是您将约束添加到 stackView
而不是 containerView
。
documentation for addConstraint
州
The constraint to be added to the view. The constraint may only reference the view itself or its subviews.
containerView
是stackView
的 super View ,而不是 subview 。
如果您更改代码以将约束添加到 containerView
它将运行
containerView.addConstraint(.init(item: stackView, attribute: .top, relatedBy: .equal, toItem: containerView, attribute: .top, multiplier: 1, constant: 0))
containerView.addConstraint(.init(item: stackView, attribute: .leading, relatedBy: .equal, toItem: containerView, attribute: .leading, multiplier: 1, constant: 0))
您可能需要添加尾随和底部约束,以便堆栈 View 填充整个容器 View 。当然,您还需要添加一个 arrangedSubview
以便堆栈 View 中实际上有一些内容。
通过引用布局指南来添加约束通常比这种旧的、更冗长的方法更简单:
import UIKit
import PlaygroundSupport
let containerView = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
containerView.backgroundColor = UIColor.white
let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
containerView.addSubview(stackView)
stackView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor).isActive = true
stackView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor).isActive = true
stackView.topAnchor.constraint(equalTo: containerView.topAnchor).isActive = true
stackView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor).isActive = true
let label = UILabel()
label.text = "Hello world"
label.textColor = .black
stackView.addArrangedSubview(label)
PlaygroundPage.current.liveView = containerView
关于ios - Swift Playground 错误 : Execution was interrupted, 原因:信号 SIGABRT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64708812/