如何在swift中创建具有多个初始值设定项的自定义UIView类?

如何在swift中创建具有多个初始值设定项的自定义UIView类?,swift,uiview,initialization,Swift,Uiview,Initialization,我正在努力坚持下去,学习它,并用Swift编写一个应用程序,而不是默认为Obj-C,尽管我一直被困在非常简单的事情上,似乎无法在网上找到答案。回去的诱惑很强烈。这就是我要做的 class CircleView : UIView { var title: UILabel convenience init(frame: CGRect, title: String) { } override init(frame: CGRect) { self.

我正在努力坚持下去,学习它,并用Swift编写一个应用程序,而不是默认为Obj-C,尽管我一直被困在非常简单的事情上,似乎无法在网上找到答案。回去的诱惑很强烈。这就是我要做的

class CircleView : UIView {

    var title: UILabel

    convenience init(frame: CGRect, title: String) {

    }

    override init(frame: CGRect) {
        self.title = UILabel.init(frame: CGRectMake(0.0, 0.0, frame.size.width, frame.size.height))
        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("CircleView is not NSCoding compliant")
    }
}

我的目标是。。。任何创建CircleView实例的人都必须同时提供一个框架和一个字符串。我怎样才能做到这一点呢?

我想你已经很接近了。方便初始值设定项可以设置标签,然后调用指定的初始值设定项:

class CircleView : UIView {

    var title: UILabel

    convenience init(frame: CGRect, title: String) {
        self.init(frame: frame)
        self.title.text = title
    }

    override init(frame: CGRect) {
        self.title = UILabel.init(frame: CGRectMake(0.0, 0.0, frame.size.width, frame.size.height))
        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("CircleView is not NSCoding compliant")
    }
}
这里唯一需要注意的是,有人仍然可以直接调用指定的初始值设定项,而不提供标签文本。如果您不想允许,我相信您可以将指定的初始值设定项设置为私有,即:

private override init(frame: CGRect) { ... }