ios - UIResponder didNotRecognizeSelector:应用程序因此错误而崩溃

标签 ios swift crash swift4.2 respondstoselector

我在App Store上的应用程序崩溃了。

以下是崩溃日志中的内容。

我的项目中有基本 View Controller 。我用基本 View Controller 扩展了每个 View Controller 。

在基本 View Controller 的viewDidAppear中,使用以下代码设置状态栏颜色。

static func adjustStatusBarToColor(colorAsString: String) {

    print("adjustStatusBarToColor===\(globalTopPadding)")

    if (globalTopPadding>=1) {
        if let statusBar: UIView = UIApplication.shared.value(forKey: "statusBar") as? UIView {
            let statusBar2: UIView = statusBar.subviews[0]
                let setForegroundColor_sel: Selector = NSSelectorFromString("setForegroundColor:")
                statusBar2.perform(setForegroundColor_sel, with: UIColor(hexString: colorAsString))
        }
    } else {
        if let statusBar: UIView = UIApplication.shared.value(forKey: "statusBar") as? UIView {
            let setForegroundColor_sel: Selector = NSSelectorFromString("setForegroundColor:")
            statusBar.perform(setForegroundColor_sel, with: UIColor(hexString: colorAsString))
        }
    }
}

知道为什么应用程序崩溃了吗?

enter image description here

最佳答案

在调用元素之前,检查元素是否响应特定的选择器,您将避免崩溃。

let setForegroundColor_sel: Selector = NSSelectorFromString("setForegroundColor:")

if statusBar2.responds(to: setForegroundColor_sel) {
    statusBar2.perform(setForegroundColor_sel, with: UIColor(hexString: colorAsString))
}

我相信这段代码返回的 View 不会响应颜色的变化:
let statusBar2: UIView = statusBar.subviews[0]

关于ios - UIResponder didNotRecognizeSelector:应用程序因此错误而崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56989240/

相关文章:

ios - 子类化 MKMapView 以提供自定义 map ?

ios - 连接ViewController和场景来展示广告(SpriteKit)

java - 尝试在 fragment 中的recyclerview中打开 Activity 时,应用程序崩溃

c - 比较2个单链接列表中的元素并进行程序崩溃(通常)

objective-c - 如何在没有 IB 的情况下控制 View 上的 UIButton

ios - 为什么它不能在 swift 2 的 Playground 上显示任何东西?

ios - UIAlertView 没有在正确的时间显示

ios - UIDynamicAnimator 停止对重力变化使用react

ios - 如何让 UIScrollView 滚动

iphone - 更改 xib 时 iPhone 上的 SIGABRT