Swift 为什么我得到一个线程1:EXC\U BAD\U访问(代码=EXC\U I386\U GPFLT)

Swift 为什么我得到一个线程1:EXC\U BAD\U访问(代码=EXC\U I386\U GPFLT),swift,exc-bad-access,Swift,Exc Bad Access,标签不应是计算属性。它应该只初始化一次。 这样做可以解决问题 var soundPoolLabel: UILabel { let label = UILabel(frame: CGRect(x: 20, y: 90, width: 540, height: 94)) label.text = "SoundPool" label.textColor = UIColor.black label.font = UIFont(name: "Bodoni 72 Oldstyle", siz

标签不应是计算属性。它应该只初始化一次。 这样做可以解决问题

var soundPoolLabel: UILabel {
  let label = UILabel(frame: CGRect(x: 20, y: 90, width: 540, height: 94))
  label.text = "SoundPool"
  label.textColor = UIColor.black
  label.font = UIFont(name: "Bodoni 72 Oldstyle", size: 80)
  let attributedString = NSMutableAttributedString(string: label.text!)
  attributedString.addAttribute(kCTKernAttributeName as NSAttributedStringKey, value: CGFloat(1.0), range: NSRange(location: 0, length: attributedString.length))
  label.attributedText = attributedString
  return label
}

soundPoolLabel.translatesAutoresizingMaskIntoConstraints = false
let topConstraint = soundPoolLabel.topAnchor.constraint(equalTo: view.topAnchor, constant: 90)
NSLayoutConstraint.activate([topConstraint])
这是因为每次使用
soundPoolLabel
,它都会创建一个新的实例,而不是使用相同的实例。
系统在子视图层次结构中找不到新实例,抛出EXC_BAD_ACCESS error

我在这里看不到足够的详细信息,无法告诉您哪一行出现了错误?在控制台中,您将看到崩溃前执行的命令列表。如果你仔细观察,它会为你指出正确的方向:你的问题所在。控制台输出的错误是lldb,仅此而已。没有告诉我是什么。产生错误的行是:NSLayoutConstraint.activate([topConstraint])try
soundPoolLabel.topAnchor.constraint(equalTo:view.topAnchor,常量:90)。isActive=true
。在我的例子中,问题在于添加计算属性。然后尝试向该属性添加约束。你帮了我谢谢!
var soundPoolLabel: UILabel = {
  let label = UILabel(frame: CGRect(x: 20, y: 90, width: 540, height: 94))
  label.text = "SoundPool"
  label.textColor = UIColor.black
  label.font = UIFont(name: "Bodoni 72 Oldstyle", size: 80)
  let attributedString = NSMutableAttributedString(string: label.text!)
  attributedString.addAttribute(kCTKernAttributeName as NSAttributedStringKey, value: CGFloat(1.0), range: NSRange(location: 0, length: attributedString.length))
  label.attributedText = attributedString
  return label
}()