github.com
以前、Objective-Cで作ったものを参考に、ちょろっとコピペすれば何とかなるだろうと思ったが、かなり甘かった。いやいや、またハマったハマった。
結果、この辺↓のTableViewの基本から作り直してみることに。一応は動くようになったが、まだ、UITableViewAutomaticDimensionというiOS8から対応のクラスに依存している。
というかだな、「.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)」のサイズ計算がデタラメになったね。SwiftだけでなくObjective-Cでも変な動作になっている。
[iOS 8/Xcode 6] SwiftではじめるiOS開発 #1 [Table View] | Developers.IO
Swift - Storyboard + Auto Layout でカスタムセルの Table View を作ったときのメモ - Qiita
Dictionary型の挙動が予想と違った。結果、構造体を使うと楽ということになった。プロパティ(インスタンス変数)特有の変な初期化縛りを意識しなくていいので、かなりやりやすい。
やりたかったことはこれ↓。Dictionaryに項番をつけたいが、Dictionary型を配列の一要素として入れるのはうまくいかず、NSMutableArrayも今更使いたくなかった。構造体いいよ、構造体。超便利。
構造体はこの辺の記事が良かった。
構造体 - swiftによるiOSアプリ開発入門
今回は、こんな感じで使った。以前はNSDictionaryとNSMutableArrayを使って書いてた。構造体いいよ、構造体。超便利。
struct strctText { var bunsyou: String var hiduke: NSDate? } class RootViewController: UITableViewController { // インスタンス変数 let textPoolArr: Array<String> = ["祇辻飴葛蛸鯖鰯噌庖箸", 〜中略〜 ,"Nam in vehicula mi."] var outputArr:[strctText]=[] //〜viewDidLoadとか中略〜 // addボタンの動作 func insertNewObject(sender : AnyObject) { // データ作成 var dataIndex: Int = Int(arc4random() % UInt32(textPoolArr.count)) let str: String = textPoolArr[dataIndex] let date = NSDate() // 構造体利用 var tempstrct = (strctText(bunsyou: str, hiduke: date)) // データ挿入(配列に構造体を格納) outputArr.insert(tempstrct, atIndex: 0) } } // セルの行数 override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return outputArr.count } // セル描画 override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // プロトタイプセルの特定 let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! CustomTableViewCell // メインラベルに文字列を設定(配列と構造体から変数取り出し) cell.bodyLabel.text = outputArr[indexPath.row].bunsyou // サブラベルに文字列を設定(配列と構造体から変数取り出し) let date: NSDate = outputArr[indexPath.row].hiduke! let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy年MM月dd日 HH時mm分ss秒" cell.dateLabel.text = dateFormatter.stringFromDate(date) return cell } // editモード時のボタンと動作 override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if (editingStyle == UITableViewCellEditingStyle.Delete) { // 配列の要素(構造体)削除 outputArr.removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } }
TableViewControllerを使っているので、override多め、tableView・delegate・dataSource紐付けなしなのであります。