Swift编译器错误:由于信号命令失败:分段错误:11

时间:2016-11-01 17:15:10

标签: swift xcode

我是Xcode和swift的新手,但我已经能够将错误源缩小到这行代码。我搜索过每一个地方但找不到解决办法。我目前正在使用Xcode 8.1。

        button.addTarget( self, action: #selector(handleRegister), for:.touchUpInside)

这是我的一些代码

import UIKit

class LoginController: UIViewController {

let backGroundImageView: UIImageView = {
    let imageView = UIImageView()
    imageView.image = UIImage(named: "backgrd_image")
    return imageView
}()

let inputsContainerView: UIView = {
    let view = UIView()
    view.backgroundColor = UIColor.white
    view.translatesAutoresizingMaskIntoConstraints = false
    view.layer.cornerRadius = 5
    view.layer.masksToBounds = true
    return view

}()

    let loginRegisterButton: UIButton = {
    let button = UIButton(type: .system)
    button.backgroundColor = UIColor(r: 80, g: 101, b: 161)
    button.setTitle("Register", for: .normal)
    button.setTitleColor(UIColor.white, for: .normal)
    button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
    button.translatesAutoresizingMaskIntoConstraints = false

    button.addTarget( self, action: #selector(handleRegister), for:.touchUpInside)
    return button
}()

// when register button is clicked, printout 123
func handleRegister() {
    print(123)

}

有没有人知道可能导致此分段错误的原因:11错误。

3 个答案:

答案 0 :(得分:2)

IMHO 原因是你在“button.addTarget(self,action:#selector(handleRegister),for:.touchUpInside)”中使用“self”。检查您是否可以插入“nil”而不是“self”。在你尝试插入“nil”之后,你可以添加“print(self)”来理解“self”并不是指你想要的“LoginController”。

答案 1 :(得分:0)

删除此行:

 button.addTarget( self, action: #selector(handleRegister), for:.touchUpInside)

并将其写入 viewDidLoad 函数

答案 2 :(得分:0)

要使用self,您必须在第一行使用“lazy var”而不是“let”,如下所示。在函数内,self引用函数“loginRegisterButton”,使用“lazy var”,self将引用你的控制器

lazy var loginRegisterButton: UIButton = {
  let button = UIButton(type: .system)
  button.backgroundColor = UIColor(r: 80, g: 101, b: 161)
  button.setTitle("Register", for: .normal)
  button.setTitleColor(UIColor.white, for: .normal)
  button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
  button.translatesAutoresizingMaskIntoConstraints = false

  button.addTarget( self, action: #selector(handleRegister), for:.touchUpInside)
return button
}()