How to specify nested custom view class?

你离开我真会死。 提交于 2019-12-03 06:00:40

At this time, I think that Interface Builder only recognizes the names of Objective-C classes. You can still make Interface Builder find a nested class with the @objc keyword:

class SuperView: UIView {
  @objc(SVNestedView) class NestedView: UIImageView {
  }
}

Then, in Interface Builder, specify that th view is of class SVNestedView. Since Objective-C isn't namespaced, you still need to pick unique names for each nested class, but at least the Swift side is properly namespaced.

In Swift, an instance of an inner class is independent of any instance of the outer class. It is as if all inner classes in Swift are declared using Java's static.

I don't think this class design suits your requirement. What you need to do is, you need to create a new class outside your view, and create some sort of a composition. This will surely work out for you.

Here is some modification to your code:

class SuperView : UIImageView {
    var text : String = "Super View"
    var nested : NestedView = NestedView()
}

class NestedView : UIImageView {
    var text : String = "Nested View"
}

I think it impossible to specify an inner class in a storyboard like SuperView.NestedView so far. So I makes a class extended from an inner class, then specifies it in a storyboard like SuperView_NestedView. It works for me.

final class SuperView_NestedView: SuperView.NestedView {} // Specifies this class in the storyboard 
class SuperView : UIImageView {

    class NestedView : UIImageView {
        var text : String = "Nested View"
    }

    var text : String = "Super View"
    var nested : NestedView?

}

This view can be referred as SuperView.NestedView from a ViewController because SuperView_NestedView is extended from SuperView.NestedView.

class TheViewController: UIViewController {
    @IBOutlet var nestedView: SuperView.NestedView!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!