gpt4 book ai didi

ios - 在运行时知道您正在 IBDesignable 中运行

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:36:24 26 4
gpt4 key购买 nike

(在 swift 2 中编程)

在我的 iOS 应用程序中,我使用了框架。我还成功地使用了 IBDesignable 功能。我在 IBDesignable 框架中有一堆 View 和按钮,因此可以很好地呈现在界面构建器的屏幕上。

问题是这些 View 之一在其初始化时执行代码,如果它仅在 IBDesignable interfacebuilder 的上下文中运行(执行只是为了呈现 IB 屏幕),则会执行断言。断言的理由是有效的,实际上并不重要,底线是我不想在“正常”操作期间失去此功能。

我的解决方案想法是知道何时执行代码只是为了在 IB 中呈现 IBDesignable 模式,从而构建一个开关以不/执行断言。

我尝试使用 #if !TARGET_INTERFACE_BUILDER 但这不起作用,因为这是一个预处理器指令,因此只评估编译时间,并且框架是预编译的(在实际应用程序中使用时)。

我也考虑过使用 prepareForInterfaceBuilder() 但这不适用,因为抛出断言的类与 UIView 本身无关。

是否有功能或任何其他方法可以在运行时(在框架中)检查您的代码是否作为 IBDesignable 模式的 IB 屏幕渲染的一部分运行?

最佳答案

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

/**
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
}

关于ios - 在运行时知道您正在 IBDesignable 中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35573613/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com