2017-09-12 12 views
0

我知道如果單元格位於某個部分的下面,就會交換單元格,因爲互聯網充滿了這個空間,但我正在爲具有兩個部分的單元格掙扎。我無法移動每個單元格,因爲顯然索引超出範圍。我認爲這將是不必要的張貼整個代碼,所以我就只粘貼在部分之間重新排列單元格

我已經宣佈了重要的位:

let sections: [String] = ["Box", "Inventory"] 
    var s1Data: [UIImage] = [] // 
    var s2Data: [UIImage] = [] //these are filled by other function 

let sectionsImages: [UIImage] = [#imageLiteral(resourceName: "blackBox"), #imageLiteral(resourceName: "blackBag")] 

var sectionData: [[UIImage]] = [] 

在viewDidLoad中():

tableView.isEditing = true 


tableView.delegate = self 
tableView.dataSource = self 

sectionData = [s1Data, s2Data] 

然後相當桌面查看功能的數量,但我不能通過一個和我說的那個:

func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) 
    { 

     let item = sectionData[sourceIndexPath.row] 
     sectionData.remove(at: sourceIndexPath.row) 
     sectionData.insert(item, at: destinationIndexPath.row) 
} 

A nd所以,交換順利,直到我試圖交換最後一個圖像單元,因爲提到的「越界」失敗。我知道我應該申報項目如下:

let item = sectionData[sourceIndexPath.section][sourceIndexPath.row] 

但是,「刪除」和「插入」呢? 我會爲你的幫助心存感激

編輯:

我做到了,雖然我不知道這是否是簡單的方法之一。總之:

func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) 
{ 
    if sourceIndexPath.section == 0 && destinationIndexPath.section == 0 
    { 
     let item = sectionData[0][sourceIndexPath.row] 
     sectionData[0].remove(at: sourceIndexPath.row) 
     sectionData[0].insert(item, at: destinationIndexPath.row) 
    } 

    else if sourceIndexPath.section == 0 && destinationIndexPath.section == 1 
    { 
     let item = sectionData[0][sourceIndexPath.row] 
     sectionData[0].remove(at: sourceIndexPath.row) 
     sectionData[1].insert(item, at: destinationIndexPath.row) 
    } 

    else if sourceIndexPath.section == 1 && destinationIndexPath.section == 0 
    { 
     let item = sectionData[1][sourceIndexPath.row] 
     sectionData[1].remove(at: sourceIndexPath.row) 
     sectionData[0].insert(item, at: destinationIndexPath.row) 
    } 

    else if sourceIndexPath.section == 1 && destinationIndexPath.section == 1 
    { 
     let item = sectionData[1][sourceIndexPath.row] 
     sectionData[1].remove(at: sourceIndexPath.row) 
     sectionData[1].insert(item, at: destinationIndexPath.row) 
    } 

    else 
    { 
     print("ERROR - SWAP MALFUNCTION") 
    } 
} 

回答

0

這是我怎麼做到的,插入使用destinationIndexPath.section:

groupItems[sourceIndexPath.section].remove(at: sourceIndexPath.row) 
groupItems[destinationIndexPath.section].insert(movedObject, at: destinationIndexPath.row) 
相關問題