一つのUITableView内で要素があまり変わらない2つ以上のセルを使い分ける
iOSのメッセージアプリの吹き出しのようなセルのように、相手と自分かで異なるUITableViewCell
を使いたいけど、中身の構成はあんまり変わらない場合の話を想定。
まず親UITableViewCell
を一つ作る
xibファイル無しで、一つUITableViewCell
を作り、全てのセルで共通のコンポーネントをプロパティで持っておく。
import UIKit
class CommonTableViewCell: UITableViewCell {
@IBOutlet weak var label: UILabel!
}
親UITableViewCell
を継承させて子UITableViewCell
を必要な種類だけ準備する
ここではATableViewCell
とBTableViewCell
を作る。
ATableViewCell
にはUILabel
とUIButton
を置いておく。
UILabel
の方は親であるCommonTableViewCell
のlabel
と紐付ける。
UIButton
の方はATableViewCell
のプロパティとして持っておく。
BTableViewCell
にはUILabel
だけ設置して、CommonTableViewCell
のlabel
と紐付ける。
現時点で、CommonTableViewCell
のlabel
にはATableViewCell
とBTableViewCell
内のUILabel
が紐付いていることになる。
使い方
まずはnibファイルを登録。
override func viewDidLoad() {
super.viewDidLoad()
var nib = UINib(nibName: "ATableViewCell", bundle: nil)
tableView.registerNib(nib, forCellReuseIdentifier: "ATableViewCell")
nib = UINib(nibName: "BTableViewCell", bundle: nil)
tableView.registerNib(nib, forCellReuseIdentifier: "BTableViewCell")
tableView.delegate = self
tableView.dataSource = self
}
tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)
内では
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let row = indexPath.row
var cell:CommonTableViewCell!
// 乱数の3の剰余が0ならATableViewCellを使う
if (rand() % 3 == 0){
var aCell = tableView.dequeueReusableCellWithIdentifier("ATableViewCell") as ATableViewCell
aCell.button.setTitle("Hoge", forState: UIControlState.Normal)
cell = aCell
} else {
cell = tableView.dequeueReusableCellWithIdentifier("BTableViewCell") as BTableViewCell
}
cell.label.text = "\(row)"
return cell
}
などというように、継承の利点を活かして各値を設定できる。
Author And Source
この問題について(一つのUITableView内で要素があまり変わらない2つ以上のセルを使い分ける), 我々は、より多くの情報をここで見つけました https://qiita.com/dr_yst/items/18740c99723f089d6e5e著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .