如何在Swift中正确创建初始值设定项?

时间:2018-04-29 15:49:07

标签: ios swift initialization

我有一个班级NewFormView: UIView,其中包含

var viewModel: NewFormViewModel

其中NewFormViewModel有初始化程序:

var user: Users
init(for user: Users) {
    self.user = user
}

所以我想:当我初始化我的NewFormView以传递user: Users并用它初始化我的viewModel时。像:

let newFormView = NewProfileFormView(user: user)

但是当我尝试为NewProfileView创建初始值设定项时:

init(user: Users) {
    super.init(user: user)
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

我收到错误Argument labels '(user:)' do not match any available overloads。我也尝试了convenience init,但又出现了另一个错误。 我认为我的问题在于思考错误。能否请您解释一下如何解决它并致电:

let newFormView = NewProfileFormView(user: user)

4 个答案:

答案 0 :(得分:0)

如果您使用.Xib文件作为视图,则可以像这样初始化UIView

var user: Users?

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    commonInit()
}

override init(frame: CGRect, user: Users) {
    super.init(frame: frame)
    commonInit()
    self.user = user
}

private func commonInit() {
    Bundle.main.loadNibNamed("yourXibName", owner: self, options: nil)
    addSubview(contentView)
    contentView.frame = self.bounds
    contentView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
}

contentView 是您班级主视图的@IBOutlet

答案 1 :(得分:0)

您需要创建另一个传递用户和框架的init,例如

    class Form: UIView {
    private var model: FormModel!
    private var user: User!

     init(user: User, frame: CGRect) {
        self.user = user
        self.model = FormModel.init(user: user)
        super.init(frame: frame) //<-- since your view is derived from UIView, you need to set your base init 
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

}

答案 2 :(得分:0)

 struct Users {
     var placeholder: String?
 }

 class NewFormView: UIView {
     var viewModel: NewFormViewModel

     init(user: Users, frame: CGRect) {
         self.viewModel = NewFormViewModel(for: user)
         super.init(frame: frame)
     }

     required init?(coder aDecoder: NSCoder) {
         fatalError("init(coder:) has not been implemented")
     }
 }

 class NewFormViewModel {
     var user: Users

     init (for user: Users) {
         self.user = user
     }
 }

示例用法:

let formView = NewFormView.init(user: Users.init(placeholder: ""), frame: CGRect())

如果用户为您的用户结构/类遵循适当的初始值设定项,并且您为帧提供了预期视图的正确尺寸。

答案 3 :(得分:0)

问题在于你如何调用

super.init(user: user)

您的NewFormViewModel初始化程序具有签名init(for :),因此您应该像这样更改代码:

super.init(for: user)