Swift練習小demo tableView 自定義cell 簡單實用
阿新 • • 發佈:2018-12-25
import UIKit class ViewController: UIViewController , UITableViewDataSource, UITableViewDelegate { var tableView : UITableView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. tableView = UITableView(frame: CGRect(x: 0, y: 30, width: self.view.bounds.size.width, height: self.view.bounds.size.height), style: UITableViewStyle.plain) tableView.delegate = self tableView.dataSource = self self.view .addSubview(tableView) tableView .register(GoodsTableViewCell.classForCoder(), forCellReuseIdentifier: "cell") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 20 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell1:GoodsTableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! GoodsTableViewCell cell1.titleLable.text = String(indexPath.row) return cell1 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { print("\(indexPath.row)") } }
import UIKit class GoodsTableViewCell: UITableViewCell { // var titleLable : UILabel? override init(style: UITableViewCellStyle, reuseIdentifier: String?){ super . init(style: style, reuseIdentifier: reuseIdentifier) self.contentView .addSubview(self.titleLable) } //懶載入label lazy var titleLable:UILabel = { let titleLable = UILabel(frame:CGRect.init(x: 100, y: 0, width: 100, height: 30)) print("----------888") titleLable.backgroundColor = .green titleLable.textAlignment = NSTextAlignment.center return titleLable }( ) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } 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 } }