我有一个CustomScrollView,其中包含UILabel的列表并在其中滚动(子类用于视图的自动定位)。在该类中,我将这些视图的列表存储为NSMutableArray。我发现,当我从数组中获取标签后索要label.view.frame.origin时,我总是得到{0,0}。因此,我用于滚动的逻辑不起作用(滚动以编程方式完成)。我试图让UILabel滚动到CustomScrollView框架的中心。这是一个代码示例,用于显示我遇到的问题:

@interface CustomScrollView : UIScrollView
@property (nonatomic) NSMutableArray* labels; //This is the array of UILabels
@end

@implementation CustomScrollView
-(void)scrollToIndex:(int)index withAnimation:(bool)animated
{
    UILabel *label = (UILabel*)self.labels[index];
    CGRect rect = CGRectMake(label.frame.origin.x - ((self.frame.size.width - label.frame.size.width) / 2), 0, self.frame.size.width, self.frame.size.height);
    [self scrollRectToVisible:rect animated:animated];
}
@end


TL:DR-label.frame.origin.x返回0,而不是相对于父视图的相对位置。
奖励-每当我实例化自定义滚动视图时,它都会自动添加两个子视图,这些子视图我都不知道其来源。我设置背景色并关闭滚动条并启用滚动。

先谢谢您的帮助。

编辑[Jun 25 11:38]-事实证明我要创建的rect滚动是正确的,但是调用[self scrollRectToVisible:rect animation:animated]却无法正常工作。

编辑[6月25日12:04]-这是每次添加子视图时调用的方法

-(UILabel*)lastLabel
{
    if (self.labels.count == 0)
        return nil;

    return (UILabel*)self.labels.lastObject;
}

-(void)adjustContentSize
{
    if (self.labels.count > 0)
    {
        float lastModifier = [self lastLabel].frame.origin.x + [self lastLabel].frame.size.width + ((self.frame.size.width - [self lastLabel].frame.size.width) / 2);
        self.contentSize = CGSizeMake(MAX(lastModifier, self.contentSize.width), self.frame.size.height);
    }
}

最佳答案

尝试使用convertRect函数:

CGRect positionOfLabelInScrollView = [self.scrollView convertRect:myLabel.frame toView:nil];
[self.scrollView setContentOffset:CGPointMake(0, topOfLabel - positionOfLabelInScrollView.origin.y + positionOfLabelInScrollView.size.height) animated:YES];


这应该滚动您的scrollView以显示标签。

关于ios - 获取ScrollView中Frame的X位置,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24412977/

10-14 20:15
查看更多