swift docsというサイトにある UITableViewに追加・削除機能を追加 という項目で、TableViewやNavigationControllerなどをstoryboardで実装して同じ機能を付けたいのですがうまくいきません。現在のViewController.swiftのコードはこちらです---
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let myItems: NSMutableArray = ["TEST1", "TEST2", "TEST3"] var myTableView: UITableView! override func viewDidLoad() { super.viewDidLoad() self.navigationItem.rightBarButtonItem = self.editButtonItem() myTableView = UITableView() myTableView.allowsSelectionDuringEditing = true myTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell") // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ return myItems.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell=tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell cell.textLabel?.text="\(myItems[indexPath.row])" return cell } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { var sec=0 sec=section+1 return "セクション"+sec.description } /* 編集ボタンが押された際に呼び出される */ override func setEditing(editing: Bool, animated: Bool) { super.setEditing(editing, animated: animated) // TableViewを編集可能にする myTableView.setEditing(editing, animated: true) // 編集中のときのみaddButtonをナビゲーションバーの左に表示する if editing { println("編集中") let addButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Add, target: self, action: "addCell:") self.navigationItem.setLeftBarButtonItem(addButton, animated: true) } else { println("通常モード") self.navigationItem.setLeftBarButtonItem(nil, animated: true) } } /* addButtonが押された際呼び出される */ func addCell(sender: AnyObject) { println("追加") // myItemsに追加. myItems.addObject("add Cell") // TableViewを再読み込み. myTableView.reloadData() } /* Cellを挿入または削除しようとした際に呼び出される */ func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { // 削除のとき. if editingStyle == UITableViewCellEditingStyle.Delete { println("削除") // 指定されたセルのオブジェクトをmyItemsから削除する. myItems.removeObjectAtIndex(indexPath.row) // TableViewを再読み込み. myTableView.reloadData() } }
}
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2015/05/14 00:19