美文网首页tableviewiOS DeveloperiOS开发
UITableView 中彻底禁止移动某行

UITableView 中彻底禁止移动某行

作者: ryang420 | 来源:发表于2016-05-31 13:12 被阅读628次

<p>
在UITableView中,我们可以使用- (BOOL) tableView: (UITableView *) tableView canMoveRowAtIndexPath: (NSIndexPath *) indexPath方法来禁止移动某一行。下面的例子是禁止移动最后一行。但是,虽然不能移动最后一行,却可以将其他行移动至最后一行下方。
</p>
<code>

  • (BOOL)tableView:(UITableView *)tableView
    canMoveRowAtIndexPath:(NSIndexPath *)indexPath
    {
    NSArray *items = [[BNRItemStore sharedStore] allItems];

    if (indexPath.row + 1 == [items count]) {
    return NO;
    }
    return YES;
    }
    </code>

<p>我们可以使用- (NSIndexPath *) tableView: (UITableView *) tableView
targetIndexPathForMoveFromRowAtIndexPath: (NSIndexPath *) source
toProposedIndexPath: (NSIndexPath *) destination 方法来彻底禁止移动最后一行,使最后一行始终位于试图的底部。例子如下:</p>

<code>
//prevent rows from being dragged to the last position:
-(NSIndexPath *) tableView: (UITableView *) tableView
targetIndexPathForMoveFromRowAtIndexPath: (NSIndexPath *) source
toProposedIndexPath: (NSIndexPath *) destination
{
NSArray *items = [[BNRItemStore sharedStore] allItems];
if (destination.row < [items count] - 1) {
return destination;
}
NSIndexPath *indexPath = nil;
// If your table can have <= 2 items, you might want to robusticize the index math.
if (destination.row == 0) {
indexPath = [NSIndexPath indexPathForRow: 1 inSection: 0];
} else {
indexPath = [NSIndexPath indexPathForRow: items.count - 2
inSection: 0];
}
return indexPath;
}
</code>

相关文章

网友评论

  • 小多多:楼主,这个方法- (BOOL)tableView:(UITableView )tableView
    canMoveRowAtIndexPath:(NSIndexPath )indexPath
    {
    NSArray items = [[BNRItemStore sharedStore] allItems];
    if (indexPath.row + 1 == [items count]) {
    return NO;
    }
    return YES;
    }
    indexPath.row + 1== [items count] 这个应该是indexPath.row == [items count],不需要+1
    遗忘国崎:最后那个代码写的不明所以,我特贴上我的代码,两行就解决了
    if (destination.row < [items count]) {
    return destination;
    }
    else{retrun sourceIndexpath;}
    遗忘国崎:@泡小泡 你自己先试一试吧
    32dbcf6aabbc:@小多多 行数和items的count不是直接相等的,是需要+1的

本文标题:UITableView 中彻底禁止移动某行

本文链接:https://www.haomeiwen.com/subject/oticdttx.html