uicollectionview - Swift Collectionview Datasource and Sections -


so, i've asked questions before, think need more here, i'm getting nowhere.

a little summary of app:

state now: users list of devices on 1 viewcontroller , can check of them want see detailed on start screen. ids of devices stored in single array this:

devarray["device1", "device2",..].

this array stored in userdefaults. urlsession server data pulled.

then pulled ,

override func collectionview(_ collectionview: uicollectionview, cellforitemat indexpath: indexpath) -> uicollectionviewcell {     let colcel = collectionview.dequeuereusablecell(withreuseidentifier: reuseidentifier, for: indexpath) as! mycollectionviewcell     let id = devarray[indexpath.row]     let devlistitem = self.devicesfromtheserver.filter { ($0["id"] as! string) == id }[0] 

the devices shown in collectionview no sections , users able rearrange cells. works good.

my intention give ability group devices in sections. thought dictionary this:

dict["device1":"sectiona", "device2":"sectiona", "device3":"sectionb"] 

but can't wrap head around how go building collectionview out of this, , i'm not sure if form of dictionary right thing do...

can please me here?

there couple of approaches adopt here. first 1 2 dimensional array array containing array of devices each section. other approach more scalable , allows model data along device name.

the second approach have included below.

what need this:

/// defines section in data source struct section {     // mark: - properties     /// title of section    let title: string     /// devices in section    var devices: [string] } 

then in view controller define array stores sections follows:

var datasource = [section(title: "section 1", devices: ["device 1"]), section(title: "section 2", devices: ["device 2","device 3"])] 

you can customise setup appending devices each section in separate functions using of logic have. have made simpler answer.

then add these collection view data source , delegate methods:

func collectionview(_ collectionview: uicollectionview, numberofitemsinsection section: int) -> int {     return datasource[section].devices.count   }  func numberofsections(in collectionview: uicollectionview) -> int {   return datasource.count }  func collectionview(_ collectionview: uicollectionview, cellforitemat indexpath: indexpath) -> uicollectionviewcell {   let cell = collectionview.dequeuereusablecell(withreuseidentifier: "cell", for: indexpath) as! mycollectionviewcell   cell.textlabel?.text = datasource[indexpath.section].devices[indexpath.row]   return cell } 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -