LoginSignup
41
15

More than 3 years have passed since last update.

UISearchBarのプライベートなプロパティにアクセスするコードがiOS 13では禁止になったようです

Posted at

「UISearchBarのプライベートなプロパティにアクセスする」とは

UISearchBartextField に色を設定するために attributedPlaceholder をセットしたいときなど、(UISearchBarに限らないが)公開されていないUI要素などにアクセスするために value(forKey:) を使う方法を使うことがあった。

searchBar.textField?.attributedPlaceholder = placeholder

extension UISearchBar {
    var textField: UITextField? {
        return value(forKey: "_searchField") as? UITextField
    }
}

iOS 13でこの方法を用いると以下のようなエラーがランタイムで発生して、アプリがクラッシュします。
「このアクセスの方法は禁止されており、アプリケーションのバグです」的なことが言われます。

*** Terminating app due to uncaught exception 'NSGenericException', reason: 'Access to UISearchBar's _searchField ivar is prohibited. This is an application bug'

iOS 13以降の対応方法

iOS 13以降では searchTextField というプロパティが外部公開されているので、次のように書いて解決させました。

extension UISearchBar {
    var textField: UITextField? {
        if #available(iOS 13.0, *) {
            return searchTextField
        } else {
            return value(forKey: "_searchField") as? UITextField
        }
    }
}

参考

41
15
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
41
15