如何在Swift中为UIView子类编写自定义init? [英] How do I write a custom init for a UIView subclass in Swift?

查看:890
本文介绍了如何在Swift中为UIView子类编写自定义init?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我想要 init a UIView 子类与 String Int



如果我只是子类化 UIView ?如果我只是做一个自定义的 init()函数,但参数是一个String和一个Int,它告诉我,super.init()如果我调用 super.init()我被告知我必须使用一个指定的初始化程序(初始化器)。



< 。我应该在那里使用什么?框架版本?编码器版本?都?为什么?

解决方案

init(frame:)初始化。您必须在初始化您的实例变量后调用它。如果这个视图正在从一个Nib重构,那么你的自定义初始化程序不会被调用,而是会调用 init(coder:)版本。因为Swift现在需要一个实现所需的 init(coder:),我更新了下面的例子,并改变了 let 变量声明为 var 和可选。在这种情况下,您将在 awakeFromNib()或稍后初始化它们。

  class TestView:UIView {
var s:String?
var i:Int?
init(s:String,i:Int){
self.s = s
self.i = i
super.init(frame:CGRect(x:0,y :0,width:100,height:100))
}

必需init(coder aDecoder:NSCoder){
super.init(coder:aDecoder)
}
}


Say I want to init a UIView subclass with a String and an Int.

How would I do this in Swift if I'm just subclassing UIView? If I just make a custom init() function but the parameters are a String and an Int, it tells me that "super.init() isn't called before returning from initializer".

And if I call super.init() I'm told I must use a designated initializer. What should I be using there? The frame version? The coder version? Both? Why?

解决方案

The init(frame:) version is the default initializer. You must call it only after initializing your instance variables. If this view is being reconstituted from a Nib then your custom initializer will not be called, and instead the init(coder:) version will be called. Since Swift now requires an implementation of the required init(coder:), I have updated the example below and changed the let variable declarations to var and optional. In this case, you would initialize them in awakeFromNib() or at some later time.

class TestView : UIView {
    var s: String?
    var i: Int?
    init(s: String, i: Int) {
        self.s = s
        self.i = i
        super.init(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
    }

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

这篇关于如何在Swift中为UIView子类编写自定义init?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆