简体   繁体   中英

Can we use a nested class for IBDesignable?

I am developing a graphic library in Swift. The code cannot be shared, but I made a sample here (see the button example, Radio buttons were dedicated to another question).

I would like to have a namespace MyGraphicLibrary for my components: MyGraphicLibrary.Button instead of MyGraphicLibraryButton

The sample pod has two classes:

// Independent class
@IBDesignable public class CustomButton: UIButton {
    ...
}

// Namespace for my components
public class MyGraphicLibrary: NSObject {

}

// Namespaced button
public extension MyGraphicLibrary {
    @objc(MyGraphicLibraryButton) @IBDesignable class Button: UIButton {
        ...
    }
}

The CustomButton class is behaving as expected in the interface builder: I can easily add the custom class to the button (see Main.storyboard ).

非嵌套自定义按钮类

For the nested class, it is not possible to set it with its normal name ( Button or MyGraphicLibrary.Button ).

The only way is to set the class @objc name MyGraphicLibraryButton ; there is no autocompletion and the module must be set to none (which looks like a nonsense, the class belongs to the GraphicLibrary module). Removing the @objc name makes no difference.

嵌套的自定义按钮类

Is there a way to make the nested class be handled correctly by the Interface Builder?

I think, in general, the answer to your question is "No" you cannot use Objective-C classes in the way you are trying to.

Interface Builder is looking for an Objective-C Class name in it's interface. Objective-C presents a flat space for class names. There is no concept of a nested namespace (which is why you end up with name prefixes like 'NS')

You are trying to impose a namespace structure using features of Swift, but that structure has no meaning to Objective-C. Even if you declare an Objective-C class in a nested Swift context, its still going to exist in the flat space of Objective-C classes.

And Interface Builder is going to pull the name from that flat space.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM