【问题标题】:Swift Playground error: Execution was interrupted, reason: signal SIGABRTSwift Playground 错误:执行被中断,原因:信号 SIGABRT
【发布时间】:2021-02-18 20:15:49
【问题描述】:

如何调试这个错误?似乎没有额外的错误描述。

失败的代码:

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.

完全错误:

错误:执行被中断,原因:信号 SIGABRT。过程 一直留在中断的地方,使用“线程 return -x" 返回表达式求值前的状态。

完整的控制台日志:

libc++abi.dylib:以 NSException 类型的未捕获异常终止

【问题讨论】:

  • 我认为那是因为您在视图实际位于层次结构之前添加了约束
  • @aheze 我试图在 containerView 初始化后立即移动 liveView 分配行,但现在在添加约束时出现相同的错误

标签: ios swift swift-playground


【解决方案1】:

问题是您将约束添加到stackView 而不是containerView

documentation for addConstraint 状态

要添加到视图的约束。约束只能引用视图本身或其子视图。

containerViewstackView 的超级视图,而不是子视图。

如果您更改代码以将约束添加到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))

您可能希望添加尾随和底部约束,以便堆栈视图填充整个容器视图。当然,您还需要添加一个arrangedSubview,以便在堆栈视图中实际存在一些内容。

通常通过引用布局指南而不是这种较旧、更冗长的方法来添加约束更简单:

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

【讨论】:

  • 成功了,谢谢。剩下的唯一主要问题是如何调试此类错误?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-21
  • 2017-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-29
  • 2017-12-26
相关资源
最近更新 更多