在Swift中的属性声明过程中引用self



我正试图用以下代码声明和初始化一个属性。

class ClassName: UIViewController {
  private let doneButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Plain, target: self, action: "doneButtonDidTapped")
   func doneButtonDidTapped() {
      println("Ulala!")
   }
}

然而,我出现了以下错误。

Cannot find an initializer for type 'UIBarButtonItem' that accepts an argument list of type '(title: String, style: UIBarButtonItemStyle, target: ClassName -> () -> ClassName, action: String)'

有人知道这里发生了什么吗?我是否应该放弃与声明内联初始化属性的尝试,转而在init()方法上进行初始化?

正如@giorashc所说,由于swift的两阶段初始化,self尚未初始化,因此无法进行初始化。

但我认为你可以创建一个懒惰的小型化:

lazy private var doneButtonItem : UIBarButtonItem = {
    [unowned self] in
    return UIBarButtonItem(title: "Done", style:UIBarButtonItemStyle.Plain, target: self, action: "doneButtonDidTapped")
    }()

@agy的答案中的闭包是不必要的,你可以(在Swift 3中):

lazy var button:UIBarButtonItem = UIBarButtonItem(title: "Title", style: .plain, target: self, action: #selector(buttonPressed(_:)))

由于swift的两阶段初始化,您需要初始化父类,然后才能在继承类中使用self

在您的实现中,self尚未由父类初始化,因此正如您所说,您应该将其移动到视图控制器的init方法,并在调用父类的初始化方法

后创建按钮

相关内容

最新更新