开发者

Is there a way to use - (UIView *)viewWithTag:(NSInteger)tag with a custom UIView

开发者 https://www.devze.com 2023-01-11 08:45 出处:网络
I have a class that inherits from UIView However when trying to use the follow (UIView *)viewWithTag:(NSInteger)tag I get the warning: *incompatible Objective-C types initializing \'struct UIView *\'

I have a class that inherits from UIView

However when trying to use the follow (UIView *)viewWithTag:(NSInteger)tag I get the warning: *incompatible Objective-C types initializing 'struct UIView *', expected 'struct CustomView '

Right now I have made a custom method that returns my custom view, the method uses a for loop with view.subviews since the views I am looking for come from the same superview. I do a conditional check if the tag matches the one I am searching for then I return 开发者_JAVA百科the view.

I suppose I am just wondering if there is a better practice to this?

Thanks


You're probably doing:

CustomView * aView = [someView viewWithTag:42];

viewWithTag: returns a UIView, not a CustomView. There are a couple ways around this:

  1. Casting. If you are absolutely sure that you'll only ever get a CustomView by doing this, then you can do:

    CustomView * aView = (CustomView *)[someView viewWithTag:42];
  2. Reflection. If you're not sure that you're going to get a custom view, then assign it into a UView reference and decide later what to do with it:

    UIView * aView = [someView viewWithTag:42];
    if ([aView isKindOfClass:[CustomView class]]) {
      CustomView * customView = (CustomView *)aView;
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消