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

时间:2019-07-11 12:29:55

标签: ios swift crash swift4.2 respondstoselector

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

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

我的项目中有基本视图控制器。我正在用基本视图控制器扩展每个视图控制器。

在基本视图控制器的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

1 个答案:

答案 0 :(得分:2)

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

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

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

我相信这段代码返回的视图不会响应颜色的变化:

let statusBar2: UIView = statusBar.subviews[0]
相关问题