2016-04-21 76 views
0

我有一個NSURL數組數組,我可以使用函數removeAtIndexinsert。我知道fromIndexPathtoIndexPath,並且此方法可以幫助我來完成使用該委託方法[[NSURL]]相同(檢查var data下圖):重新排列UIImage陣列中的元素

func moveDataItem(fromIndexPath : NSIndexPath, toIndexPath: NSIndexPath) { 
     let name = self.data[fromIndexPath.section][fromIndexPath.item] 
     self.data[fromIndexPath.section].removeAtIndex(fromIndexPath.item) 
     self.data[toIndexPath.section].insert(name, atIndex: toIndexPath.item) 

    // do same for UIImage array 
} 

然而,我的UIImage與3個空元素的數組與跑步。

var newImages = [UIImage?]() 

viewDidLoad() { 
    newImages.append(nil) 
    newImages.append(nil) 
    newImages.append(nil) 
} 

我的問題是我怎麼可以使用newImages陣列內moveDataItem(),還有data並能夠運行爲重新安排爲UIImage的排列順序線。

我想這些只可惜我不能讓他們工作..

self.newImages[fromIndexPath.section].removeAtIndex(fromIndexPath.item) 
// and 
self.newImages[fromIndexPath.row].removeAtIndex(fromIndexPath.item) 

爲了澄清,數據陣列看起來像這樣

lazy var data : [[NSURL]] = { 

    var array = [[NSURL]]() 
    let images = self.imageURLsArray 

    if array.count == 0 { 

     var index = 0 
     var section = 0 


     for image in images { 
      if array.count <= section { 
       array.append([NSURL]()) 
      } 
      array[section].append(image) 

      index += 1 
     } 
    } 
    return array 
}() 
+0

所以,你想的是一般繞二維陣列移動的方法? – PeejWeej

+0

是的,我想要做同樣的事情,我也爲'UIImage array'在moveDataItem()裏面爲數據做'..' – senty

回答

2

這應該重新安排任何工作2d陣列:

func move<T>(fromIndexPath : NSIndexPath, toIndexPath: NSIndexPath, items:[[T]]) -> [[T]] { 

    var newData = items 

    if newData.count > 1 { 
     let thing = newData[fromIndexPath.section][fromIndexPath.item] 
     newData[fromIndexPath.section].removeAtIndex(fromIndexPath.item) 
     newData[toIndexPath.section].insert(thing, atIndex: toIndexPath.item) 
    } 
    return newData 
} 

用法示例:

var things = [["hi", "there"], ["guys", "gals"]] 

// "[["hi", "there"], ["guys", "gals"]]\n" 
print(things) 

things = move(NSIndexPath(forRow: 0, inSection: 0), toIndexPath: NSIndexPath(forRow:1, inSection: 0), items: things) 

// "[["there", "hi"], ["guys", "gals"]]\n" 
print(things) 

,這將與正常工作數組:

func move<T>(fromIndex : Int, toIndex: Int, items:[T]) -> [T] { 

    var newData = items 

    if newData.count > 1 { 
     let thing = newData[fromIndex] 
     newData.removeAtIndex(fromIndex) 
     newData.insert(thing, atIndex: toIndex) 
    } 
    return newData 
} 
+0

它是一個委託函數,一切適用於'data'。問題在於調整'moveDataItem()'中的UIImage數組。我想你讓我錯了。 :/我編輯了我的問題一點,以澄清更多 – senty

+0

是的,我重新讀你的問題,並注意到這一點。爲一維數組添加了一個函數 – PeejWeej

+0

因此,我應該創建另一個委託方法(您的最後一個示例),並在調用moveDataItem方法時調用它?這是正確的方法嗎?我想用新的順序覆蓋UIImage陣列。 – senty