ios - How to add a cell to my Table View dynamically using a button -
i trying add cell table view button. have read , watched suggests have written should work, doesn't. suggestions?
import uikit class rootviewcontroller: uitableviewcontroller, uitableviewdatasource, uitableviewdelegate { private var cellpointsize: cgfloat! private var albumslist: albumlist! private var albums:[album]! private let albumcell = "album" @iboutlet var mytableview: uitableview! override func viewdidload() { super.viewdidload() let preferredtableviewfont = uifont.preferredfontfortextstyle(uifonttextstyleheadline) cellpointsize = preferredtableviewfont.pointsize albumslist = albumlist.sharedalbumlist albums = albumslist.albums self.mytableview.datasource = self self.mytableview.delegate = self } override func viewwillappear(animated: bool) { super.viewwillappear(animated) tableview.reloaddata() } // mark: - table view data source override func tableview(tableview: uitableview, numberofrowsinsection section: int) -> int { // return number of rows in section. return albums.count } override func tableview(tableview: uitableview, titleforheaderinsection section: int) -> string? { return "albums" } override func tableview(tableview: uitableview, cellforrowatindexpath indexpath: nsindexpath) -> uitableviewcell { let cell = mytableview.dequeuereusablecellwithidentifier(albumcell, forindexpath: indexpath) as! uitableviewcell //cell.textlabel?.font = fontfordisplay(atindexpath: indexpath) cell.textlabel?.text = albums[indexpath.row].name cell.detailtextlabel?.text = albums[indexpath.row].artist return cell } @ibaction func addnewalbumaction(sender: uibarbuttonitem) { var newalbum = album(namein: "new title", yearin: "new year", artistin: "new artist", labelin: "new label") albumslist.addalbum(newalbum) dispatch_async(dispatch_get_main_queue(), { () -> void in self.mytableview.reloaddata() }) } func savedata(albumobject: album) { var archivearray = nsmutablearray(capacity: albums.count) in albums { var albumencodedobject = nskeyedarchiver.archiveddatawithrootobject(a) archivearray.addobject(albumencodedobject) } var userdata = nsuserdefaults() userdata.setobject(archivearray, forkey: "albums") userdata.synchronize() }
my albums array adding data correctly. can see albums in debugger. delegate methods never being called after first time when app loads. ideas?
in tableview:numberofrowsinsection:
, returns albums.count
but when button pressed, add new album
albumslist
the problem is, albums
not update.
so think should return albumslist.albums.count
instead.
and in tableview:cellforrowatindexpath:
, modify cell correspond albumslist.albums[indexpath.row]
Comments
Post a Comment