環境 Xcode12 Swift5
StoryBoardは使わず、 XibでCustomCellをオートレイアウトで生成しています。
拡張管理しやすいアーキテクチャにしました。
ViewController
import UIKit
final class ViewController: UIViewController {
let vm = TableObject()
lazy var tView: TableView = {
let tView = TableView()
tView.table.register(TableViewCell.identifier, forCellReuseIdentifier: "cell")
tView.table.delegate = self
tView.table.dataSource = vm
return tView
}()
override func viewDidLoad() {
super.viewDidLoad()
tView.frame = view.frame
view.addSubview(tView)
}
}
//MARK: UITableViewDelegate
extension ViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("1234567890")
}
}
UIView
import UIKit
final class TableView: UIView {
let table = UITableView()
override init(frame: CGRect) {
super.init(frame: frame)
self.frame = UIScreen.main.bounds
table.frame = self.frame
addSubview(table)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
NSObject
import UIKit
final class TableObject: NSObject { }
//MARK: UITableViewDataSource
extension TableObject: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
cell.config(image: UIImage(named:"PhSHT2L7_400x400")!)
return cell
}
}
UITableViewCell
import UIKit
final class TableViewCell: UITableViewCell {
static let identifier: UINib = UINib(nibName: "TableViewCell", bundle: nil)
@IBOutlet weak var tableImageView: UIImageView!{
didSet{
tableImageView.clipsToBounds = true
tableImageView.layer.cornerRadius = 12
}
}
@IBOutlet weak var shadowView: UIView!{
didSet{
shadowView.layer.cornerRadius = 12
shadowView.backgroundColor = UIColor.brown
shadowView.layer.shadowOpacity = 0.5
shadowView.layer.shadowRadius = 12
shadowView.layer.shadowColor = UIColor.black.cgColor
shadowView.layer.shadowOffset = CGSize(width: 5, height: 5)
}
}
func config(image: UIImage){
tableImageView.image = image
}
}