//自定义个叫 HomeTableViewCell 的 cell
import UIKit
class HomeTableViewCell:UITableViewCell{
var nameLabel = UILable()override init(style: UITableViewCellStyle, reuseIdentifier: String?){super.init(style: style, reuseIdentifier: reuseIdentifier)if !self.isEqual(nil) {nameLabel.font = UIFont.systemFontOfSize(15)self.contentView.addSubview(nameLabel)nameLabel.snp_makeConstraints{make inmake.top.equalTo(20)make.leading.equalTo(60)make.width.equalTo(200)make.height.equalTo(20)}}}required init?(coder aDecoder: NSCoder) {fatalError("init(coder:) has not been implemented")}override func awakeFromNib() {super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {super.setSelected(selected, animated: animated)
// Configure the view for the selected state}
}
}
//HomeViewController.swift
class HomeViewController: UIViewController,UITableViewDelegate,UITableViewDataSource{var homeTableView:UITableView = UITableView()override func viewDidLoad() {super.viewDidLoad()homeTableView.delegate = selfhomeTableView.dataSource = selfhomeTableView.backgroundColor = UIColor.orangeColor()homeTableView.registerClass(HomeTableViewCell.classForCoder(), forCellReuseIdentifier: "homeCell")self.view.addSubview(homeTableView)homeTableView.snp_makeConstraints{make inmake.top.equalTo(105)make.leading.equalTo(10)make.trailing.equalTo(-10)make.bottom.equalTo(-53)}}func numberOfSectionsInTableView(tableView: UITableView) -> Int {return 1}func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {return 16}func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {var cell:HomeTableViewCell = tableView.dequeueReusableCellWithIdentifier("homeCell", forIndexPath: indexPath) as! HomeTableViewCellif cell.isEqual(nil) {cell = HomeTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "homeCell")}cell.nameLabel.text = "baby"return cell
}func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {return 50}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {print("row : \(indexPath.row)")}}
用 swift 纯代码自定义 TableViewCell ,以及自定义 cell 在 TableView 中的调用
最新推荐文章于 2022-04-01 15:01:46 发布