如何为我的标签添加 class?

How do I give my label a class?

我以编程方式创建了一个标签-

var label = UILabel(frame: CGRect(x: 31, y: 169, width: 258, height: 258))
label.textAlignment = NSTextAlignment.Center
label.text = ""
label.backgroundColor = UIColor.blackColor()
self.view.addSubview(label)

我还创建了一个 Cocoa Touch Class 文件,它是 UILabel 的子class。该文件覆盖了 drawRect 方法。我想让这个文件成为我创建的标签的 class。我怎样才能做到这一点?

你可以这样做:

var classLbl = YourClass()  //instead of using UILabel use your class.
classLbl.frame = CGRectMake(31, 169, 258, 258)
classLbl.textAlignment = NSTextAlignment.Center
classLbl.text = ""
//and so on

当你在 subclassing 某些东西时,这意味着你在 "expanding" 你的 "parent" 的功能上 - 在你的情况下 UILabel - 并且制作 "expanding" =39=].一些Class的功能扩展方法有很多,但这是最基本的方法。

当你创建你的子class时,你基本上是在说"append those functions to parent",如果它们相同,覆盖它们(这就是你需要override关键字的原因)。

在你的例子中,你创建了 UILabel 的子class 可能是这样的:

class MyLabel : UILabel {

    override func drawRect(rect: CGRect) {

        // Your drawing code
    }
}

如果你想使用它,你只需要为你的变量分配不同的 class ;你的 MyLabel:

var label = MyLabel(frame: CGRectZero)

MyLabel class自动继承UILabel中的所有构造函数、变量和方法,因此您可以像以前一样使用所有以前的功能。

注意:虽然是不同的数据类型,如果你有方法:

func useMyLabel(label : UILabel) {

     // Do something with my label
}

您仍然可以使用您的对象来填充 "label" 参数,因为它是 UILabel 的子项。在这种情况下,您将无法访问您创建的 "extra" 方法,除非您将变量强制类型转换为您的类型,如下所示:

let myLabel = label as! MyLabel

如果您想了解有关继承的更多信息,Apple Documentation provides everything there is about how it works in swift, or wikipedia article 内容相当广泛,不仅提供了有关 Class 继承的更多信息。