简体   繁体   English

我们可以为 IBDesignable 使用嵌套类吗?

[英]Can we use a nested class for IBDesignable?

I am developing a graphic library in Swift.我正在 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我想为我的组件使用命名空间MyGraphicLibraryMyGraphicLibrary.Button而不是MyGraphicLibraryButton

The sample pod has two classes:示例 pod 有两个类:

// 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 ). CustomButton类在界面构建器中的行为符合预期:我可以轻松地将自定义类添加到按钮(请参阅Main.storyboard )。

非嵌套自定义按钮类

For the nested class, it is not possible to set it with its normal name ( Button or MyGraphicLibrary.Button ).对于嵌套类,无法使用其正常名称( ButtonMyGraphicLibrary.Button )对其进行设置。

The only way is to set the class @objc name MyGraphicLibraryButton ;唯一的方法是设置类@objc 名称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).没有自动完成功能,模块必须设置为none (这看起来像废话,该类属于 GraphicLibrary 模块)。 Removing the @objc name makes no difference.删除@objc 名称没有区别。

嵌套的自定义按钮类

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.我认为,总的来说,您的问题的答案是“不”,您不能以您尝试的方式使用 Objective-C 类。

Interface Builder is looking for an Objective-C Class name in it's interface. Interface Builder 正在其接口中寻找 Objective-C 类名称。 Objective-C presents a flat space for class names. Objective-C 为类名提供了一个扁平的空间。 There is no concept of a nested namespace (which is why you end up with name prefixes like 'NS')没有嵌套命名空间的概念(这就是为什么你最终会使用像“NS”这样的名称前缀)

You are trying to impose a namespace structure using features of Swift, but that structure has no meaning to Objective-C.您正在尝试使用 Swift 的功能强加命名空间结构,但该结构对 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.即使你在嵌套的 Swift 上下文中声明了一个 Objective-C 类,它仍然会存在于 Objective-C 类的平面空间中。

And Interface Builder is going to pull the name from that flat space. Interface Builder 将从该平面空间中提取名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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