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

后端 未结 2 767
独厮守ぢ
独厮守ぢ 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.

提交回复
热议问题