[swift] tableView カスタムセルの作成
目次
tableView カスタムセルの作成
StoryBoard
StoryBoardにTableViewCellを新たに配置
identiferに好きな名前をつける。例:newCell
UITableViewCell.swiftを新規作成
UITableViewCellを継承したswiftファイルを作成
サンプルコード:
class customTableViewCell: UITableViewCell {
@IBOutlet weak var profileView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var detailLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
/// 画像・タイトル・説明文を設定するメソッド
func setCell(str: String,detail:String) {
titleLabel.text = str
detailLabel.text = detail
}
func setCell(img: UIImage) {
profileView.image = img
}
}
StoryBoardとcustomTableViewCellを関連付け
StoryBoardのカスタムセルに
@IBOutlet weak var profileView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var detailLabel: UILabel!
に対応するアイテムを配置。
それぞれの紐付けを行う
また
StoryBoardのカスタムセルには「customTableViewCell」を指定しておくこと。
tableView
tableViewに以下のコードを実装
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("newCell") as! customTableViewCell
cell.setCell(UIImage(named: "clubList_user_icon.png")!)
cell.setCell("titleString",detail:"detailString")
return cell
}