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

时间:2018-07-24 00:39:49

标签: 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", 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])

1 个答案:

答案 0 :(得分:1)

标签不应该被收购。它应该只初始化一次。 做这样的事情来解决它

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时,它将创建一个新实例,而不是使用同一实例。 系统在出现EXC_BAD_ACCESS错误的子视图中找不到新实例