Using `valueForKey` to access view in UIBarButtonItem, private API violation?

后端 未结 2 693
独厮守ぢ
独厮守ぢ 2020-12-19 03:03

Since UIBarButtonItem doesn\'t subclass UIView, it\'s impossible to get at the normal characteristics like its frame.

One way

相关标签:
2条回答
  • 2020-12-19 03:42

    Five Pieces of Evidence for "It's Not Private"

    • It's a property that you can get to in other ways. Try this and one of those views is, in fact, the _view ivar of the UIBarButtonItem in question. This indicates that access to this UIView is not prohibited itself, though the KVO way in might be questionable (but I doubt it).

        NSArray *array = self.toolBar.subviews;
        for (UIView *view in array) {
            view.backgroundColor = UIColor.greenColor;
        }
      
    • They actually trigger the KVO for this property. ivars do not have to trigger the KVO API, right?

    • @Farcaller mentions a similar case which is for sale in the App Store. Since he/she answered within the first 20 minutes of the question being up there, it's reasonable (but not safe!) to assume that there might be thousands of apps in the App Store that do this.

    • This UIView gets subbed out each time the button is pressed, so you cannot just, for example, set a gesture recognizer on it and be done. You can, however, keep setting the same gesture recognizer every time the view gets replaced. To me, this is actually more evidence that it's not a private API thing, but rather you have to be very careful when using it (and use KVO to make sure you have the latest one).

    • My app is for sale in the App Store and does this.

    0 讨论(0)
  • 2020-12-19 03:45

    This is not private in terms of immediate rejection upon validation, but it's private enough to be considered fragile (that is, new iOS version can break your existing app in the app store that's using the code).

    I can say, that a similar code (fetching backgroundView ivar of UIToolbar via KVC) has passed app store validation and is being used in production.

    In case of possible bad things, you must wrap the method in @try { ... } @catch, so that you intercept KVC possibly failing in newer iOS release.

    0 讨论(0)
提交回复
热议问题