Swift练习小demo tableView 自定义cell 简单实用

来源:互联网 发布:枪林弹雨刷枪软件 编辑:程序博客网 时间:2024/06/04 18:13
import UIKitclass 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 UIKitclass 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    }}

0 0
原创粉丝点击