iOS 數組移動元素,其他元素自動移位

- (void)moveArrayItemFromIndex:(int)fromIndex toIndex:(int)toIndex{
    
    NSMutableArray *array = @[@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9"].mutableCopy;
    NSString *str = array[fromIndex];
    NSInteger currentIndex = fromIndex;
    if (fromIndex <= toIndex) {
        for (int i=fromIndex; i<toIndex; i++) {
            currentIndex = [array indexOfObject:str];
            if (currentIndex < toIndex) {
                [array exchangeObjectAtIndex:currentIndex withObjectAtIndex:currentIndex + 1];
                currentIndex++;
            }
        }
    }else{
        for (int i=fromIndex; i>toIndex; i--) {
            currentIndex = [array indexOfObject:str];
            if (currentIndex > toIndex) {
                [array exchangeObjectAtIndex:currentIndex withObjectAtIndex:currentIndex - 1];
                currentIndex--;
            }
        }
    }
    
    NSLog(@"%@",array);
    
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章