您的位置:首页 > 移动开发 > Swift

Swift 4.0 纯代码实现UITableView

2018-02-01 17:46 423 查看
class ViewControllerI:
UIViewController,UITableViewDelegate,UITableViewDataSource {

var mytableView : UITableView?

let testValue:NSString = "这是测试内容\n这是测试内容\n这是测试内容\n这是测试内容\n这是测试内容\n这是测试内容\n这是测试内容\n这是测试内容\n这是测试内容\n这是测试内容\n这是测试内容\n这是测试内容\n这是测试内容\n这是测试内容"

override func viewDidLoad() {
super.viewDidLoad()

view.backgroundColor = UIColor.gray

mytableView = UITableView(frame: CGRect(x: 0, y: 64, width: view.frame.width, height: view.frame.height) , style: .plain)
mytableView?.tableFooterView = UIView()
mytableView?.delegate = self             // 设置代理
mytableView?.dataSource = self
mytableView?.estimatedRowHeight = 60
mytableView?.rowHeight = UITableViewAutomaticDimension
view .addSubview(mytableView!)

//注册UITableView,cellID为重复使用cell的Identifier
mytableView?.register(UITableViewCell.self, forCellReuseIdentifier: "cellID")

}

/*
@注意:我们前边的ViewController继承了UITableViewDataSource
@和 UITableViewCelegate。如果我们不注册下面的三个方法XCode就会报错!!!
*/

// 列数
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
// 行数
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}

// 创建 UITableViewCell
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cells = (tableView.dequeueReusableCell(withIdentifier: "cellID", for: indexPath)) as UITableViewCell
cells.textLabel?.text = testValue as String
return cells
}

// 点击响应事件
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

tableView.deselectRow(at: indexPath, animated: true)
}

// 分割线无间距
override func viewDidLayoutSubviews() {
mytableView?.separatorInset = .zero
mytableView?.layoutMargins = .zero
}

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.separatorInset = .zero
cell.layoutMargins = .zero
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  swift