【精】表格(UITableView)总结(5):表单元(UITableViewCell

转载请声明出处:

1、前言

UITableView 中显示的每一个单元都是一个 UITableViewCell 对象。因为在 tableView 快速滑动的滑动的过程中,频繁的 alloc 对象是比较费时的,于是引入了 cell 的重用机制。UITableViewCell 默认3种显示样式,如果需要自定义 Cell 有多种方式,此处只具体介绍纯代码方式:

步骤1:新建 MyCell.swift 类继承 UITableViewCell;

步骤2:重写MyCell 的 init 方法,自定义属性(如果希望对已有属性 textLabel、detailTextLabel 等进行重新布局,重写 layoutSubviews 方法);

步骤3:在 cellForRowAtIndexPath 中使用 MyCell 替换原有的 UITableViewCell,此时 MyCell 中自定义的属性可自行设置。

2、演示代码

MyCell.swift

//// MyCell.swift// UITableViewSample-UITableViewCell//// Created by jinnchang on 15/5/21.// Copyright (c) 2015年 Jinn Chang. All rights reserved.//import UIKitclass MyCell: UITableViewCell {var newLabel: UILabel?// 新属性在此定义override init(style: UITableViewCellStyle, reuseIdentifier: String?) {super.init(style: style, reuseIdentifier: reuseIdentifier)self.contentView.backgroundColor = UIColor.whiteColor()newLabel = UILabel(frame: CGRectMake(180, 0, 80, self.frame.size.height))self.contentView.addSubview(newLabel!)}required init(coder aDecoder: NSCoder) {fatalError("init(coder:) has not been implemented")}// 重新布局override func layoutSubviews() {self.textLabel?.frame = CGRectMake(20, 0, 80, self.frame.size.height)self.detailTextLabel?.frame = CGRectMake(100, 0, 80, self.frame.size.height)}}ViewController.swift//// ViewController.swift// UITableViewSample-UITableViewCell//// Created by jinnchang on 15/5/21.// Copyright (c) 2015年 Jinn Chang. All rights reserved.//import UIKitclass ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {var tableView: UITableView!override func viewDidLoad() {super.viewDidLoad()// Do any additional setup after loading the view, typically from a nib.tableView = UITableView(frame: CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height), style: UITableViewStyle.Plain)tableView.delegate = selftableView.dataSource = selfself.view.addSubview(tableView)}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, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {var cell = tableView.dequeueReusableCellWithIdentifier("cell") as? MyCellif(cell == nil) {cell = MyCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "cell")}cell!.textLabel?.text = "\(indexPath.row)"cell!.detailTextLabel?.text = "\(indexPath.row)"cell!.newLabel?.text = "\(indexPath.row)"return cell!}}Github上项目地址:https://github.com/jinnchang/SwiftSamples/blob/master/UITableViewSample-UITableViewCell3、结语

文章最后更新时间:2015年5月23日16:12:32

,在乎的是沿途的风景以及看风景的心情,让心灵去旅行!

【精】表格(UITableView)总结(5):表单元(UITableViewCell

相关文章:

你感兴趣的文章:

标签云: