定位uicontrol以创建无限滚动

时间:2014-09-08 12:12:11

标签: ios objective-c scroll uicontrol uicontrolview

我是目标C学习编程的初学者,也是初学者在本网站上提问,请耐心等待。

我目前正在尝试在屏幕上绘制一列方框(UIControls),并能够无限向上或向下滚动它们。因此当一个人离开屏幕的底部时,它会移到底部并重新使用。

我知道代码中肯定会有很多错误。但我想要做的主要是:盒子都在一个数组(imArray)。当一个盒子从屏幕底部滚动时,它从阵列的末端取下,并在开头插入。然后该框将其自身以图形方式插入到列的顶部。

第一个if语句处理滚动屏幕底部,它工作正常。但第二个if声明,我尝试与相似的代码做相反的工作只有当我慢慢滚动时,当我快速滚动时,框之间的间距变得不均匀,有时一个框只是锁定在屏幕上并停止移动。

感谢任何帮助,我将尝试提供可能需要的更多清晰度。

-(BOOL)continueTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event
{

CGPoint pt = [touch locationInView:self];
int yTouchEnd = pt.y;
int yTouchChange = yTouchEnd - yTouchStart;

//iterate through all boxes in imArray
for(int i = 0; i < self.numberOfSections; i++)
{
    //1. get box
    STTimeMarker *label = self.imArray[i];
    //2. calculate new label transform
    label.transform = CGAffineTransformTranslate(label.startTransform, 0, yTouchChange);
    CGRect frame = label.frame;
    //3. if the box goes out of the screen on the bottom 
    if (frame.origin.y > [[UIScreen mainScreen]bounds].size.height)
    {

        //1. move box that left the screen to to beginning of array
        [self.imArray removeObjectAtIndex:i];
        [self.imArray insertObject:label atIndex:0];
        //2. get y value of box closest to top of screen. 
        STTimeMarker *labelTwo = self.imArray[1];
        CGRect frameTwo =labelTwo.frame;
        //3. put box that just left the screen in front of the box I just got y value of. 
        frame.origin.y = frameTwo.origin.y - self.container.bounds.size.height/self.numberOfSections;
        label.frame=frame;
     }

    //1. if the box goes out of the frame on the top
    // (box is 40 pixels tall)
    if (frame.origin.y < -40)
    {  
        [self.imArray removeObjectAtIndex:i];
        [self.imArray addObject:label];
        STTimeMarker *labelTwo = self.imArray[self.numberOfSections-1];
        CGRect frameTwo =labelTwo.frame;
        frame.origin.y = frameTwo.origin.y + self.container.bounds.size.height/self.numberOfSections;

        label.frame=frame;

    }
}

return YES;
}

1 个答案:

答案 0 :(得分:0)

如果我理解你正在努力做的事情,我想你想以不同的方式来实现。您的数据模型(数组)不需要更改。滚动时所有正在改变的是视图,屏幕上显示的内容。实现无限滚动外观的最简单方法是使用UITableView并为其提供大量单元格。然后,您的cellForRowAtIndexPath:方法将使用mod运算符(%)返回正确位置的单元格。未经测试的代码:

- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section {
    return 99999;
}

- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {
    NSInteger moddedRow = indexPath.row % [self.imArray count];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kSomeIdentifierConst forIndexPath:[NSIndexPath indexPathForRow:moddedRow inSection:indexPath.section]];
    return [self configureCellWithData:self.imArray[moddedRow]];
}

如果您需要真正的无限滚动,这可能不足以满足您的目的,但是应该可以用于大多数目的。