【swift】iosで画面の回転を検知してUITableViewを再描画する
はじめに
今回やりたかったのは画面一杯にUITableViewをセット。
端末の向きが変更されたら画面サイズに合わせてUITableViewの幅と高さを更新。ということ
なにも対応しないと縦向きから横向きにしたときにテーブルの幅が半分くらいになってしまうので対応が必要
実装
class SampleViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
setView()
}
func setView() {
tableView = UITableView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height))
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "TableViewCell")
tableView.delegate = self
tableView.dataSource = self
view.addSubview(tableView)
}
// 端末の向き変更を検知
override func viewDidAppear(_ animated: Bool) {
NotificationCenter.default.addObserver(self, selector: #selector(self.onOrientationChange(notification:)),name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
}
// 向きが変わったらframeをセットしなおして再描画
func onOrientationChange(notification: NSNotification){
tableView.frame.size = CGSize(width: view.frame.width, height: view.frame.height)
tableView.setNeedsDisplay()
tableView.reloadData()
}
・・・
}これでやりたいことはできた。
以上です