在斯威夫特的财产申报期间提到自我

时间:2015-06-24 08:23:13

标签: ios swift

我正在尝试使用以下代码声明和初始化属性。

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()方法上进行初始化?

3 个答案:

答案 0 :(得分:6)

正如@giorashc所说,由于快速的两阶段初始化,自我尚未初始化,所以你不能这样做。

但我认为你可以创建一个懒惰的inialization:

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

答案 1 :(得分:2)

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

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

答案 2 :(得分:1)

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

在您的实现中,self尚未由父类初始化,因为您说应该将其移动到视图控制器的init方法并在调用父级的初始化方法后创建按钮

相关问题