user1855952
user1855952

Reputation: 1575

Casting UIViews to custom Views

So I have a UIScrollView that is populated with a series of MyCustomViews that are subclasses of a standard UIView. In the delegate callback "scrollViewDidScroll I am trying to loop through all the subviews and call a specific function on them but I don't think the typecasting is working. Here is my code below:

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{

    for(UIView *subView in [scrollView subviews){

        MyCustomView *customView = (MyCustomView *)subView;
        [customView myMethod];
    }
}

When I call "myMethod" on customView, the program crashes saying an unrecognized selector was sent to instance. I believe that my type-casting is the issue as the method myMethod works in other situations. So how do I remedy this situation?

Upvotes: 0

Views: 1822

Answers (2)

TotoroTotoro
TotoroTotoro

Reputation: 17622

Solution 1:

If you do the following, you don't even need to cast your object to MyCustomView *. It can be of any type, e.g. UIView.

if([subView respondsToSelector:@selector(myMethod)]) {
    [subView performSelector:@selector(myMethod)];
}

Solution 2:

You can check the object type before doing the cast.

if([subView isKindOfClass:[MyCustomView class]]) {
    MyCustomView *customView = (MyCustomView *)subView;
    [customView myMethod];
}

Upvotes: 5

Nekak Kinich
Nekak Kinich

Reputation: 934

For "catch" this issue, use

if([customView respondsToSelector:@selector(myMethod)]){
    [customView myMethod];
}

and with this, the app don't crash.

Also in your for use for(MyCustomView* customView in [scrollView subviews]){

Upvotes: 0

Related Questions