iOS ~ 1盆繁、UITableView的cell掀淘,上、下移動時使用drag油昂、drop繁疤;2、UICollectionView的cell移動位置:

一秕狰、UITableView上下移動位置(系統(tǒng)):

1、在UITableView中躁染,我們可以使用- (BOOL) tableView: (UITableView *) tableView canMoveRowAtIndexPath: (NSIndexPath *) indexPath;方法來禁止移動某一行鸣哀。下面的例子是禁止移動最后一行。但是吞彤,雖然不能移動最后一行我衬,卻可以將其他行移動至最后一行下方。

二饰恕、UITableView上下移動位置(系統(tǒng)):

1挠羔、第一種:不用drag和drop

代碼:

[self.tableView setEditing:YES animated:YES]; // 進(jìn)入可編輯狀態(tài)
//默認(rèn)編輯模式下,每個cell左邊有個紅色的刪除按鈕埋嵌,設(shè)置為None即可去掉
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleNone;
}

//是否允許indexPath的cell移動
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        return NO;
    } else {
        return YES;
    }
}

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
    
    
    NSMutableArray *dataArray = [NSMutableArray arrayWithCapacity:0];
//    dataArray = [self.listModels mutableCopy];
//
//    // 當(dāng)結(jié)束移動時破加,判斷結(jié)束時的位置,把移動的元素刪除再加到結(jié)束的位置
//    if (sourceIndexPath.row < self.listModels.count) {
//
//        GWCityManageListModel *userModel = self.listModels[sourceIndexPath.row];
//        [dataArray removeObjectAtIndex:sourceIndexPath.row];
//
//        if (destinationIndexPath.row >= dataArray.count) {
//            [dataArray addObject:userModel];
//        } else {
//            [dataArray insertObject:userModel atIndex:destinationIndexPath.row];
//        }
//
//    }
//    self.listModels  = [dataArray copy];
//
//    // 改變保存的值
//    [[NSUserDefaults standardUserDefaults] setObject:self.listModels forKey:@"saveSort_CityManage_CityWeather_Arr"];
    
    
    NSLog(@"移動的位置索引 = %ld,\n 將要移動到達(dá)的位置索引 == %ld", sourceIndexPath.row, destinationIndexPath.row);
    //更新數(shù)據(jù)源
}

#pragma mark -- 禁止某一行移動
// 禁止某一行移動雹嗦,并且禁止其他cell移動到該cell的索引位置(這里禁止移動第一行)
- (NSIndexPath *)tableView:(UITableView *)tableView targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath {
    
    NSIndexPath *indexPath = nil;
    
    // 要求:第一個cell位置置頂范舀,不可移動,所以當(dāng)移動其他cell到該位置時了罪,進(jìn)行下列操作:
    if (proposedDestinationIndexPath.row == 0) {
        indexPath = [NSIndexPath indexPathForRow: 1 inSection: 0];
    } else {
        indexPath = [NSIndexPath indexPathForRow: proposedDestinationIndexPath.row inSection: 0];
    }
    return indexPath;
}
2锭环、第二種,使用 drag和drop

需要遵守和實現(xiàn)UITableViewDragDelegateUITableViewDropDelegate代理和其代理方法:
在UITableView中泊藕,我們可以使用- (BOOL) tableView: (UITableView *) tableView canMoveRowAtIndexPath: (NSIndexPath *) indexPath方法來禁止移動某一行辅辩。下面的例子是禁止移動最后一行。但是,雖然不能移動最后一行玫锋,卻可以將其他行移動至最后一行下方蛾茉。
所以需要方法:- (NSIndexPath *)tableView:(UITableView *)tableView targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath;來設(shè)置。
遵守協(xié)議:

    <UITableViewDragDelegate, UITableViewDropDelegate>
//    [self.tableView setEditing:YES animated:YES]; // 進(jìn)入可編輯狀態(tài)
    self.tableView.dragDelegate = self; // drag 拖拉代理
    self.tableView.dropDelegate = self; // drop
    self.tableView.dragInteractionEnabled = YES; // 打開拖拽功能
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width/375*20, [UIScreen mainScreen].bounds.size.width/375*15, [UIScreen mainScreen].bounds.size.width/375*335, [UIScreen mainScreen].bounds.size.height - k_Height_StatusBar - k_Height_NavContentBar - [UIScreen mainScreen].bounds.size.width/375*(75 + 15)) style:UITableViewStyleGrouped];
    self.tableView.backgroundColor = RGBA(248, 249, 250, 1);
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.dragDelegate = self; // drag 拖拉代理
    self.tableView.dropDelegate = self; // drop
    self.tableView.dragInteractionEnabled = YES; // 打開拖拽功能
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.backView addSubview:self.tableView];
//默認(rèn)編輯模式下景醇,每個cell左邊有個紅色的刪除按鈕臀稚,設(shè)置為None即可去掉
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleNone;
}

//是否允許indexPath的cell移動
//是否允許indexPath的cell移動
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) { // 禁止第一行移動
        return NO;
    } else {
        return YES;
    }
}

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
    
    
    NSMutableArray *dataArray = [NSMutableArray arrayWithCapacity:0];
    dataArray = [self.listModels mutableCopy];
    
    // 當(dāng)結(jié)束移動時,判斷結(jié)束時的位置三痰,把移動的元素刪除再加到結(jié)束的位置
    if (sourceIndexPath.row < self.listModels.count) {
        
        GWCityManageListModel *userModel = self.listModels[sourceIndexPath.row];
        [dataArray removeObjectAtIndex:sourceIndexPath.row];
        
        if (destinationIndexPath.row >= dataArray.count) {
            [dataArray addObject:userModel];
        } else {
            [dataArray insertObject:userModel atIndex:destinationIndexPath.row];
        }
        
    }
    self.listModels  = [dataArray copy];
    
    
    /**
     連續(xù)使用交換位置方法:exchangeObjectAtIndex吧寺,
     
    例子: 當(dāng)前index和index+1交換,一直交換到目標(biāo)位置
    數(shù)組:12345散劫,21345稚机,23145,23415获搏,23451
    移動“1”的位置赖条,前移就是減(index-1),后移就是加(index+1)
     
     // 交換位置:exchangeObjectAtIndex常熙,在這里不使用
     [dataArray exchangeObjectAtIndex:destinationIndexPath.row withObjectAtIndex:sourceIndexPath.row];
     */
    
    
//    // 從數(shù)組中讀取需要移動行的數(shù)據(jù)
//    id  object = [dataArray objectAtIndex:fromRow];
//    // 在數(shù)組中移動需要移動的行的數(shù)據(jù)
//    [dataArray removeObjectAtIndex:fromRow];
//    // 把需要移動的單元格數(shù)據(jù)在數(shù)組中纬乍,移動到想要移動的數(shù)據(jù)前面
//    [dataArray insertObject:object atIndex:toRow];
    
    NSLog(@"移動的位置索引 = %ld,\n 將要移動到達(dá)的位置索引 == %ld", sourceIndexPath.row, destinationIndexPath.row);
    //更新數(shù)據(jù)源
}

#pragma mark -- 禁止某一行移動
// 禁止某一行移動,并且禁止其他cell移動到該cell的索引位置(這里禁止移動第一行)
- (NSIndexPath *)tableView:(UITableView *)tableView targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath {
    
    NSIndexPath *indexPath = nil;
    
    // 要求:第一個cell位置置頂裸卫,不可移動仿贬,所以當(dāng)移動其他cell到該位置時,進(jìn)行下列操作:
    if (proposedDestinationIndexPath.row == 0) {
        indexPath = [NSIndexPath indexPathForRow: 1 inSection: 0];
    } else {
        indexPath = [NSIndexPath indexPathForRow:proposedDestinationIndexPath.row inSection: 0];
    }
    return indexPath;
}

#pragma mark -- <UITableViewDragDelegate>

// 拖拽 預(yù)覽
- (nullable UIDragPreviewParameters *)tableView:(UITableView *)tableView dragPreviewParametersForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // 可以在該方法內(nèi)使用 貝塞爾曲線 對單元格的一個具體區(qū)域進(jìn)行裁剪
    UIDragPreviewParameters *parameters = [[UIDragPreviewParameters alloc] init];

    CGRect rect = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width/375*(375 - 48), [UIScreen mainScreen].bounds.size.width/375*(100));
    parameters.visiblePath = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:[UIScreen mainScreen].bounds.size.width/375*16];
    parameters.backgroundColor = RGBA(248, 249, 250, 0.3);
    return parameters;
}

- (void)tableView:(UITableView *)tableView dragSessionWillBegin:(id<UIDragSession>)session {
    // 將要 拖拽
    NSLog(@"????");
}

- (void)tableView:(UITableView *)tableView dragSessionDidEnd:(id<UIDragSession>)session {
    // 拖拽 結(jié)束
    NSLog(@"????");
}

/**
 當(dāng)接收到添加item響應(yīng)時墓贿,會調(diào)用該方法向已經(jīng)存在的drag會話中添加item
 如果需要茧泪,可以使用提供的點(在集合視圖的坐標(biāo)空間中)進(jìn)行其他命中測試。
 如果該方法未實現(xiàn)聋袋,或返回空數(shù)組队伟,則不會將任何 item 添加到拖動,手勢也會正常的響應(yīng)
 */
- (nonnull NSArray<UIDragItem *> *)tableView:(nonnull UITableView *)tableView itemsForBeginningDragSession:(nonnull id<UIDragSession>)session atIndexPath:(nonnull NSIndexPath *)indexPath {
    return nil;
//    return @[[[UIDragItem alloc] initWithItemProvider:[NSItemProvider new]]];
    
//    NSItemProvider *itemProvider = [[NSItemProvider alloc] initWithObject:self.dataSource[indexPath.item]];
//    UIDragItem *item = [[UIDragItem alloc] initWithItemProvider:itemProvider];
//    return @[item];
}

// 確保實現(xiàn)該UITableViewDragDelegate方法幽勒,并返回YES嗜侮。這將確保拖放必須發(fā)生在同一個應(yīng)用程序中。
- (BOOL)tableView:(UITableView *)tableView dragSessionIsRestrictedToDraggingApplication:(id<UIDragSession>)session {
    return YES;
}

#pragma mark -- <UITableViewDropDelegate>
// 松手 預(yù)覽
- (nullable UIDragPreviewParameters *)tableView:(UITableView *)tableView dropPreviewParametersForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // 可以在該方法內(nèi)使用 貝塞爾曲線 對單元格的一個具體區(qū)域進(jìn)行裁剪
    UIDragPreviewParameters *parameters = [[UIDragPreviewParameters alloc] init];
    
    CGRect rect = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width/375*(375 - 48), [UIScreen mainScreen].bounds.size.width/375*(100));
    parameters.visiblePath = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:[UIScreen mainScreen].bounds.size.width/375*16];
    parameters.backgroundColor = RGBA(248, 249, 250, 0.3);
    return parameters;
}

- (void)tableView:(UITableView *)tableView dropSessionDidExit:(id<UIDropSession>)session {
    
}

- (void)tableView:(UITableView *)tableView dropSessionDidEnd:(id<UIDropSession>)session {
    
}

- (void)tableView:(nonnull UITableView *)tableView performDropWithCoordinator:(nonnull id<UITableViewDropCoordinator>)coordinator {
    
}

二啥容、UICollectionView的cell移動位置:

原理:先刪除棘钞,再插入(注意:判斷最后到達(dá)的位置的索引號,是否大于數(shù)組的數(shù)量干毅,大于的話使用addObject:宜猜,小于的話使用:insertObject: atIndex:

WechatIMG342.jpeg

第三方:https://github.com/lxcid/LXReorderableCollectionViewFlowLayout

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市硝逢,隨后出現(xiàn)的幾起案子姨拥,更是在濱河造成了極大的恐慌绅喉,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,640評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件叫乌,死亡現(xiàn)場離奇詭異柴罐,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)憨奸,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,254評論 3 395
  • 文/潘曉璐 我一進(jìn)店門革屠,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人排宰,你說我怎么就攤上這事似芝。” “怎么了板甘?”我有些...
    開封第一講書人閱讀 165,011評論 0 355
  • 文/不壞的土叔 我叫張陵党瓮,是天一觀的道長。 經(jīng)常有香客問我盐类,道長寞奸,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,755評論 1 294
  • 正文 為了忘掉前任在跳,我火速辦了婚禮枪萄,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘猫妙。我一直安慰自己瓷翻,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,774評論 6 392
  • 文/花漫 我一把揭開白布吐咳。 她就那樣靜靜地躺著,像睡著了一般元践。 火紅的嫁衣襯著肌膚如雪韭脊。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,610評論 1 305
  • 那天单旁,我揣著相機(jī)與錄音沪羔,去河邊找鬼。 笑死象浑,一個胖子當(dāng)著我的面吹牛蔫饰,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播愉豺,決...
    沈念sama閱讀 40,352評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼篓吁,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了蚪拦?” 一聲冷哼從身側(cè)響起杖剪,我...
    開封第一講書人閱讀 39,257評論 0 276
  • 序言:老撾萬榮一對情侶失蹤冻押,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后盛嘿,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體洛巢,經(jīng)...
    沈念sama閱讀 45,717評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,894評論 3 336
  • 正文 我和宋清朗相戀三年次兆,在試婚紗的時候發(fā)現(xiàn)自己被綠了稿茉。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,021評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡芥炭,死狀恐怖漓库,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情蚤认,我是刑警寧澤米苹,帶...
    沈念sama閱讀 35,735評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站砰琢,受9級特大地震影響蘸嘶,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜陪汽,卻給世界環(huán)境...
    茶點故事閱讀 41,354評論 3 330
  • 文/蒙蒙 一训唱、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧挚冤,春花似錦况增、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,936評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至澜薄,卻和暖如春为肮,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背肤京。 一陣腳步聲響...
    開封第一講書人閱讀 33,054評論 1 270
  • 我被黑心中介騙來泰國打工颊艳, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人忘分。 一個月前我還...
    沈念sama閱讀 48,224評論 3 371
  • 正文 我出身青樓棋枕,卻偏偏與公主長得像,于是被迫代替她去往敵國和親妒峦。 傳聞我的和親對象是個殘疾皇子重斑,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,974評論 2 355

推薦閱讀更多精彩內(nèi)容