- 追加された行はこの色です。
- 削除された行はこの色です。
#author("2016-05-30T14:42:04+09:00","default:wikiwriter","wikiwriter")
#author("2018-02-07T13:47:55+09:00","default:wikiwriter","wikiwriter")
[[UIKit/テーブル]]
&tag(UIKit/テーブル/セルのカスタマイズ);
*目次 [#gd626c5c]
#contents
*関連ページ [#sbb107cd]
*参考情報 [#xa37e514]
*ストーリーボードで設定したプロトタイプセルを利用する [#nbc22bb9]
-参考: [[[iOS] Auto Layout + Storyboard で高さ可変のUITableViewCellを作成する | Developers.IO:http://dev.classmethod.jp/smartphone/iphone/how-to-make-adjustable-cell/]]
-コードじゃなくてストーリーボードでカスタムセルを使用することができる。
-追加したプロトタイプセルのスタイルをBasicにすれば通常のセルのように使うこともできる。
**手順 [#ie11db94]
-ストーリーボードでUITableViewにUITableViewCellをドロップ(これがプロトタイプセルと呼ばれる)。
-UITableViewCellのセルを自作のクラスに変更。例MyCell。
-ストーリーボード上でセルにラベルなどを配置して、MyCellにアウトレットなどを設定。
#pre{{
class MyCell: UITableViewCell {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var descriptionLabel: 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
}
}
}}
-このセルを呼び出す。
#pre{{
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as! MyCell
cell.titleLabel?.text = rows[indexPath.row]
// cell.textLabel?.text = rows[indexPath.row]
return cell
}
}}
*カスタマイズしたセルのマージンを調節する [#p46d6e8d]
**UILabelを設置する場合 [#nd9c03a2]
-UITableViewCellにUILabelを設置した場合、左側のマージンがデバイスによって変わってしまう問題。
-[[ios - Matching left alignment of custom & standard UITableViewCell types - Stack Overflow:http://stackoverflow.com/questions/29349917/matching-left-alignment-of-custom-standard-uitableviewcell-types]]
-ContentViewとUITableViewCellのPreserve Superview Marginsをtrueに設定し、UILabelのマージンをmarginに対して0とすればよい。
**UITextViewを設置する場合 [#he7bfe07]
-基本的にUILabelの場合と同じだが、内部の隙間が存在する。以下の設定で揃えられる
textView.textContainer.lineFragmentPadding = 0
*その他 [#k19dba8f]
**セルの背景色を変更する [#af032deb]
-cellForRowAtで変更で以下のように変更するサンプルコードが多数見つかる。
#pre{{
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath)
cell.textLabel?.text = rows[indexPath.row]
cell.textLabel?.backgroundColor = UIColor.gray
return cell
}
}}
-しかしこのコードではスクロールしないと、背景がうまく変更できない場合がある(Initial View Controllerの場合これで良いが、そこからモーダル表示した場合はだめ?)
-その場合以下のようにwillDisplayで設定しないとだめらしい。
#pre{{
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.textLabel?.backgroundColor = UIColor.lightGray
}
}}