【问题标题】:Programmatically scroll UIScrollView using subview element使用子视图元素以编程方式滚动 UIScrollView
【发布时间】:2014-01-19 22:34:32
【问题描述】:

我想知道如何使用子视图 UILabel 访问 UIScrollView。

我尝试使用.superview 访问 UIScrollView;但是我现在收到一个错误

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

我使用的代码如下所示

- (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];

}

【问题讨论】:

    标签: ios uiscrollview uilabel superview


    【解决方案1】:

    UILabel 的父视图属于UIView 类型,因此不会响应您尝试调用的方法。您可以将 superview 转换为 UIScrollView,以便 Xcode 可以看到您尝试访问的方法和属性。您还应该检查 superview 是否响应该方法。

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

    鉴于您的示例代码,您还需要强制转换超级视图以获取 contentOffset

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

    【讨论】:

    • XCode 也不喜欢该代码。看来我将不得不找到另一种访问它的方法。只是我在多个滚动视图中有多个 UILabels,它们放置在 UITableViewCells 中。所以我有一个 UIScrollviews 表作为它们的单元格,我试图找出要滚动的 UIScroll 视图。
    • @HurkNburkS 我已经扩展了我的答案,包括将超级视图也转换为 UIScrollView ——这可能是 Xcode 所抱怨的。试试看。
    猜你喜欢
    • 2011-01-15
    • 1970-01-01
    • 1970-01-01
    • 2014-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多