[Swift] テーブルのヘッダーをカスタマイズ。画像のせたり、高さを調整したり。
tableのheaderをカスタマイズしたいときってあると思います。imageのせたりsize調整したり。(本当は、スクロール位置によって高さが変わるような、可変にしたいと思っているのですが、それは次回..。)
ViewController.swift
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let myItems = ["test1", "test2", "test3"]
var myTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
let barHeight: CGFloat = UIApplication.sharedApplication().statusBarFrame.size.height
let displayWidth: CGFloat = self.view.frame.width
let displayHeight: CGFloat = self.view.frame.height
myTableView = UITableView(frame: CGRect(x: 0, y: barHeight, width: displayWidth, height: displayHeight - barHeight))
myTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "MyCell")
myTableView.dataSource = self
myTableView.delegate = self
// ⦿ ここでヘッダーの高さを指定
myTableView.sectionHeaderHeight = 300
self.view.addSubview(myTableView)
}
/*
⦿ ヘッダーの設定
*/
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
// ⦿ UIViewを返します。
// ⦿ UIViewの上にUIImageViewを貼り付けます。
let myView: UIView = UIView()
myView.backgroundColor = UIColor.greenColor()
let myImageView = UIImageView(frame: CGRectMake(0, 0, 100, 50))
myImageView.contentMode = UIViewContentMode.Center
myImageView.backgroundColor = UIColor.yellowColor()
myImageView.layer.position = CGPoint(x: self.view.frame.width/2, y: 100.0)
myImageView.image = UIImage(named: "oil_king.png")
myView.addSubview(myImageView)
return myView
}
/*
行数
*/
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myItems.count
}
/*
セル作成
*/
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("MyCell")
cell!.textLabel?.text = myItems[indexPath.row]
return cell!
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
複数セッションがある場合は、ヘッダーの高さの指定は、
myTableView.sectionHeaderHeight = 300
ではなくて、
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 300
}
とかを、使えばいけるような気がしております。1つだったらどっちを使っても大丈夫そうでした。
Author And Source
この問題について([Swift] テーブルのヘッダーをカスタマイズ。画像のせたり、高さを調整したり。), 我々は、より多くの情報をここで見つけました https://qiita.com/mochizukikotaro/items/f37241163e85e058ce4a著者帰属:元の著者の情報は、元の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 .