Подтвердить что ты не робот

UITableView: как отключить перетаскивание элементов в определенную строку?

У меня есть UITableView с перетаскиваемыми строками, и я могу добавлять/удалять элементы. Источником данных является NSMutableArray.

Теперь, если я перемещаю строку с помощью "Добавить новую функциональность", приложение выходит из строя, потому что dataSource меньше, поскольку такая строка еще не добавлена.

Итак, я изменил этот код:

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
        if (indexPath.row >= [dataList count]) return NO;
        return YES;
    }

И теперь я больше не могу двигаться. Однако я могу по-прежнему перемещать другие строки после такой строки и, следовательно, сбой кода.

Как я могу это решить? Есть ли способ отключить перетаскивание "в" определенных строк, а не только из?

спасибо

4b9b3361

Ответ 1

Это именно то, что метод UITableViewDelegate

-tableView:targetIndexPathForMoveFromRowAtIndexPath:toProposedIndexPath:

это для. Подойдет ли это вашим целям? Здесь документация.

Ответ 2

Предыдущие ответы и документация (см. this и , как упоминалось в других ответах) полезны, но неполны. Мне нужно:

  • примеры
  • знать, что делать, если предлагаемый ход не подходит

Без дальнейших церемоний, вот некоторые

Примеры

Принять все ходы

- (NSIndexPath *)tableView:(UITableView *)tableView
    targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath
                         toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath
{
    return proposedDestinationIndexPath;
}

Отклонить все ходы, возвращая строку в исходное положение

- (NSIndexPath *)tableView:(UITableView *)tableView
    targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath
                         toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath
{
    return sourceIndexPath;
}

Отклонить некоторые ходы, возвращая любую отклоненную строку в ее исходное положение

- (NSIndexPath *)tableView:(UITableView *)tableView
    targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath
                         toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath
{
    if (... some condition ...) {
        return sourceIndexPath;
    }
    return proposedDestinationIndexPath;
}

Ответ 3

Как сделать исправление последней строки:

- (NSIndexPath *)tableView:(UITableView *)tableView
targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath
       toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath
{
    // get number of objects
    NSUInteger numberOfObjects = [[[BNRItemStore sharedStore] allItems] count]; 

    if ( (proposedDestinationIndexPath.row+1==numberOfObjects) || (sourceIndexPath.row+1==numberOfObjects) ) {
        NSLog(@"HERE");
        return sourceIndexPath;
    }
    else{
         NSLog(@"count=%d %d", [[[BNRItemStore sharedStore] allItems] count], proposedDestinationIndexPath.row);
        return proposedDestinationIndexPath;
    }
}

Ответ 4

Ниже приведен пример ограничения перетаскивания до 0-го индекса 1-го раздела UICollectionView:

func collectionView(_ collectionView: UICollectionView, dropSessionDidUpdate session: UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UICollectionViewDropProposal {

    if session.localDragSession != nil {
        // Restricts dropping to 0th index
        if destinationIndexPath?.row == 0 {
           return UICollectionViewDropProposal(operation: .forbidden) 
        }

        if collectionView.hasActiveDrag {
            return UICollectionViewDropProposal(operation: .move, intent: .insertAtDestinationIndexPath)
        } else {
            return UICollectionViewDropProposal(operation: .copy, intent: .insertAtDestinationIndexPath)
        }
    }        
}

func collectionView(_ collectionView: UICollectionView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
    // Prevents dragging item from 0th index
    if indexPath.row == 0 {
        return [UIDragItem]() // Prevents dragging item from 0th index
    }

    let item = self.yourArray[indexPath.row]
    let itemProvider = NSItemProvider(object: item)
    let dragItem = UIDragItem(itemProvider: itemProvider)
    dragItem.localObject = item
    return [dragItem]
}