为什么我得到一个线程 1:EXC_BAD_ACCESS(代码 = EXC_I386_GPFLT)

Gil*_*ist 5 exc-bad-access swift

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])
Run Code Online (Sandbox Code Playgroud)

Man*_*bba 14

标签不应是计算属性。它应该只初始化一次。做这样的事情来解决这个问题。

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
}()
Run Code Online (Sandbox Code Playgroud)

这样做的原因是因为每次使用时soundPoolLabel,它都会创建它的一个新实例,而不是使用相同的实例。系统在子视图层次中找不到新实例,抛出EXC_BAD_ACCESS错误