iosuiscrollviewuilabelsuperview

Programmatically scroll UIScrollView using subview element


I would like to know how to access a UIScrollView using a subview UILabel.

I have tried to access the UIScrollView using .superview; however I am now receiving an error

No visible @interface for 'UIView' declares the selector 'scrollRectToVisible:animated:'

The code I am using looks like this

- (void) SymbolButtonPressed:(NSString *)selectedString {

    UILabel *label = (UILabel *)[self.view viewWithTag:currentlySelectedTag];

// perform scrolling here, figure out what view your uilable is in.
    float newPosition = label.superview.contentOffset.x+label.frame.size.width;
    CGRect toVisible = CGRectMake(newPosition, 0, label.superview.frame.size.width, label.superview.frame.size.height);

    [label.superview scrollRectToVisible:toVisible animated:YES];

}

Solution

  • The superview of a UILabel is of type UIView and so does not respond to the method you are trying to call. You can cast the superview as a UIScrollView so that Xcode can see the methods and properties you are trying to access. You should also check if the superview responds to the method.

    if([label.superview respondsToSelector:@selector(scrollRectToVisible:animated:)]) {
        [(UIScrollView *)label.superview scrollRectToVisible:toVisible animated:YES];
    }
    

    Given your sample code you will also need to cast the superview to get contentOffset

    float newPosition = ((UIScrollView *)label.superview).contentOffset.x+label.frame.size.width;