如何使用按钮动态添加单元格到我的表视图

时间:2015-07-18 06:24:24

标签: ios swift uitableview

我正在尝试使用按钮将单元格添加到表格视图中。我所阅读和观看的所有内容都表明我所写的内容应该有效,但事实并非如此。有什么建议吗?

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 the number of rows in the 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)
    for a in albums {
        var albumEncodedObject = NSKeyedArchiver.archivedDataWithRootObject(a)
        archiveArray.addObject(albumEncodedObject)
    }

    var userData = NSUserDefaults()
    userData.setObject(archiveArray, forKey: "albums")
    userData.synchronize()
}

我的相册数组正在正确添加数据。我可以在调试器中看到专辑。在应用程序加载后第一次调用委托方法。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

tableView:numberOfRowsInSection:

,它会返回albums.count

但是按下按钮后,您可以将新的album添加到albumsList

问题是,albums无法获得更新。

所以我认为你应该返回albumsList.albums.count

并在tableView:cellForRowAtIndexPath:中修改与albumsList.albums[indexPath.row]

对应的单元格