Created
February 19, 2019 08:08
-
-
Save yoheiMune/b07c1c1be1ad11dbb71f0db0e882c7f7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CommentViewController : UITableViewController { | |
// 投稿データ. | |
var post: Post? | |
// コメントデータ. | |
var comments: [Comment] = [] | |
// 表示する際に呼び出される. | |
override func viewDidLoad() { | |
// タイトル. | |
self.title = "コメント一覧" | |
// コメントを読み込んで、表示する. | |
self.loadCommentList() | |
} | |
// コメントデータをAPIから取得して、画面に表示する. | |
fileprivate func loadCommentList() { | |
// アンラップ. | |
guard let post = self.post else { | |
return | |
} | |
// APIコール. | |
Api.getComments(postId: post.id) { errorMessage, comments in | |
// エラーがあれば表示して終わり. | |
if let errorMessage = errorMessage { | |
self.showAlert(message: errorMessage) | |
return | |
} | |
// コメントの一覧を表示する. | |
if let comments = comments { | |
self.comments = comments | |
self.tableView.reloadData() | |
} | |
} | |
} | |
} | |
// TableView 関連の処理 | |
extension CommentViewController { | |
// セクション数. | |
override func numberOfSections(in tableView: UITableView) -> Int { | |
// 1セクション:Postの本文を表示 | |
// 2セクション:コメント一覧を表示 | |
return 2 | |
} | |
// セクションごとの行数. | |
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { | |
// Postの本文の場合、1つで固定. | |
if section == 0 { | |
return 1 | |
} | |
// コメント一覧の場合は、コメント数分だけ表示. | |
return self.comments.count | |
} | |
// 表示セルの生成. | |
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { | |
// セルを生成. | |
let cell = UITableViewCell() | |
// 1セクション目の場合. | |
if indexPath.section == 0 { | |
cell.textLabel?.text = self.post?.body | |
} else { | |
// 2セクション目の場合は、コメントを表示. | |
let comment = self.comments[indexPath.row] | |
cell.textLabel?.text = comment.comment | |
} | |
// 返却. | |
return cell | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment