Reordering Elements inside Array of UIImage

安稳与你 提交于 2019-12-12 02:49:11

问题


I have an array of NSURL array, and I am able to use functions removeAtIndex and insert. I know the fromIndexPath and toIndexPath and this method helps me to accomplish the same for [[NSURL]] using this Delegate method (check var data below):

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
}

However, I have an array of UIImage with 3 empty elements with running.

var newImages = [UIImage?]()

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

My question is how can I use the newImages array inside moveDataItem(), as well as the data and be able to run that lines for rearranging the order for UIImage array.

I tried these but unfortunately I couldn't make them work..

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

For clarification, the data array looks like this

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
}()

回答1:


This should work for rearranging any 2d array:

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
}

example usage:

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)

And this will work with a normal array:

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
}


来源:https://stackoverflow.com/questions/36757509/reordering-elements-inside-array-of-uiimage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!