【问题标题】:Inserting cell in the middle of a uitableview在uitableview中间插入单元格
【发布时间】:2012-09-17 06:55:08
【问题描述】:

在我的 ipad 应用程序中,我需要拖放一个 UIButton 来插入一个单元格。我设法通过 touchupinside 事件拖动一个按钮并插入一个单元格。它适用于以下代码 -

//button1 is initially placed in a view called scrollview
[button1 addTarget:self action:@selector(imageMoved:withEvent:) forControlEvents:UIControlEventTouchDragInside];

[button1 removeTarget:self action:@selector(insertcell) forControlEvents:UIControlEventTouchUpInside];

CGPoint pointfordeterminingrow;

- (IBAction) imageMoved:(UIButton *) sender withEvent:(UIEvent *) event {

    CGPoint point = [[[event allTouches] anyObject] locationInView:self.view];
    UIControl *control = sender;
    control.center = point;

    pointfordeterminingrow=point;   // point where the button is hovering now

    if ([sender state] == UIGestureRecognizerStateBegan) {

        [self.view addSubview:sender];

    }

    if ([sender state] == UIGestureRecognizerStateChanged) {

        [scrollview addSubview:sender];

    }

    if ([sender state] == UIGestureRecognizerStateEnded) {

        [scrollview addSubview:sender];

    }

}

- (int)rowAtPoint:(CGPoint)point {

    NSIndexPath* newIndexPath = [MainTableView indexPathForRowAtPoint:point];
    return newIndexPath == nil ? [items count] : newIndexPath.row;

     //items is a mutable array has the content of each cell
}

-(void)insertcell {

    int row = [self rowAtPoint:pointfordeterminingrow];

    NSIndexPath* newIndexPath = [NSIndexPath indexPathForRow:row inSection:0];

    [self insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath                 indexPathForRow:newIndexPath.row inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
}

这些代码在 indexpath 中插入一个单元格,在该单元格上方放置按钮 //touchuped 方法被调用。

我的问题是:

我得到的“newIndexPath”是一个数字(表格视图中的行),按钮被放置在该数字上。这种“insertcell”方法在 tableview 不滚动的情况下可以正常工作,

当 TableView 滚动时,“rowAtPoint”返回一个数字,该数字是 indexpath 处的行,现在是可见的。

换句话说,如果按钮被放在 indexpath 58 上方并且如果上面隐藏了 50 个单元格(通过滚动),我得到数字 8,(不是 58)

因此,当按钮在 indexpath 58 处被放置时,一个单元格被插入到 INDEXPATH 8 处。

我需要一些建议来获取 tableview 中的 EXACT indexpath。前提是“点”是 self.view 中的 CGPoint。

【问题讨论】:

    标签: iphone objective-c ios ipad uitableview


    【解决方案1】:

    试试这个:

    int row = [self rowAtPoint:pointfordeterminingrow];
    
    [myTableView visibleCells];  // call this first to avoid possible iOS bug in next statement
    NSArray *visIndexPaths = [myTableView indexPathsForVisibleRows]; 
    
    
    NSIndexPath* newIndexPath = [visIndexPaths objectAtIndex:row];
    

    【讨论】:

    • 谢谢兄弟 :) 这个完全符合我的要求 :) 非常感谢
    猜你喜欢
    • 1970-01-01
    • 2011-04-10
    • 1970-01-01
    • 2015-10-30
    • 1970-01-01
    • 2018-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多