swift2 在运行时知道您正在IBDesignable中运行

vwhgwdsa  于 2022-11-06  发布在  Swift
关注(0)|答案(2)|浏览(187)

(在swift 2中编程)
在我的iOS应用程序中,我使用了框架。我也非常成功地使用了IBDesignable特性。我在框架中有一堆视图和按钮是IBDesignable的,因此在界面构建器的屏幕上呈现得很好。
问题是,这些视图中的一个在初始化时执行代码,如果它只在IBDesignable interfacebuilder的上下文中运行,则会执行Assert(执行该Assert只是为了呈现IB屏幕)。Assert的原因是有效的,而且真的不重要,底线是我不想在“正常”操作期间失去此功能。
我对解决方案的想法是知道代码何时被执行,以便在IB for IBDesignable模式下呈现,从而构建一个开关来不/执行Assert。
我尝试使用#if!TARGET_INTERFACE_BUILDER,但这不起作用,因为这是一个预处理器指令,因此只计算编译时间,并且框架是预编译的(当在实际应用中使用时)。
我也考虑过使用prepareForInterfaceBuilder(),但这并不适用,因为抛出Assert的类与UIView本身无关。
是否有一个函数或任何其他方法来检查在运行时(在一个框架中),你的代码正在运行的IB屏幕渲染的一部分,为IBDesignable模式?

wtzytmuj

wtzytmuj1#

在测试了几十个解决方案之后,我发现以下解决方案可以可靠地工作:

/**
 Returns true if the code is being executed as part of the Interface Builder IBDesignable rendering,
 so not for testing the app but just for rendering the controls in the IB window. You can use this
 to do special processing in this case.

* /

public func runningInInterfaceBuilder() -> Bool {
    //get the mainbundles id
    guard let bundleId = NSBundle.mainBundle().bundleIdentifier else {
        //if we don't have a bundle id we are assuming we are running under IBDesignable mode
        return true
    }
    //when running under xCode/IBDesignable the bundle is something like
    //com.apple.InterfaceBuilder.IBCocoaTouchPlugin.IBCocoaTouchTool
    //so we check for the com.apple. to see if we are running in IBDesignable rendering mode
    //if you are making an app for apple itself this would not work, but we can live with that :)
    return bundleId.rangeOfString("com.apple.") != nil
}
vuktfyat

vuktfyat2#

SWIFT 4版

/**
     Returns true if the code is being executed as part of the Interface Builder IBDesignable rendering,
     so not for testing the app but just for rendering the controls in the IB window. You can use this
     to do special processing in this case.
     */
    public func runningInInterfaceBuilder() -> Bool {
        //get the mainbundles id
        guard let bundleId = Bundle.main.bundleIdentifier else {
            //if we don't have a bundle id we are assuming we are running under IBDesignable mode
            return true
        }
        //when running under xCode/IBDesignable the bundle is something like
        //com.apple.InterfaceBuilder.IBCocoaTouchPlugin.IBCocoaTouchTool
        //so we check for the com.apple. to see if we are running in IBDesignable rendering mode
        //if you are making an app for apple itself this would not work, but we can live with that :)
        return bundleId.contains("com.apple.")
    }

相关问题