小编use*_*178的帖子

如何在Swift中从字符串实例化class和init?

我可以在ObjC中从string中实例化类.例如,我通过子类化UITableViewCell定义了新的DBCell类,并使用这些代码从name实例化类:

 DBCell *cell=[tableView dequeueReusableCellWithIdentifier:cellClassname];
    if (cell==nil) {
        Class cellClass=NSClassFromString(cellClassname);
        cell=[cellClass alloc];
        cell=[cell initWithStyle:cellStyle reuseIdentifier:cellClassname];
    }
Run Code Online (Sandbox Code Playgroud)

现在我需要将代码迁移到Swift,我在Swift中重新定义了DBCell类:

 class DBCell: UITableViewCell {
    var label:String?
    var key:String?
    var managedObject:NSManagedObject?
    var delegate:AnyObject?
    convenience override init(style: UITableViewCellStyle, reuseIdentifier: String!) {
        self.init(style: style, reuseIdentifier: reuseIdentifier)
        self.textLabel.font=UIFont.preferredFontForTextStyle(UIFontTextStyleCaption1)
        self.backgroundColor=UIColor.blackColor()
        self.textLabel.backgroundColor=UIColor.blackColor()
    }
    }
Run Code Online (Sandbox Code Playgroud)

但是我如何实例化类并调用相应的init函数?

class instantiation swift

8
推荐指数
1
解决办法
4828
查看次数

标签 统计

class ×1

instantiation ×1

swift ×1