一、自定义表视图(UITableView)
import UIKit
class HoMetableView: UITableView,UITableViewDataSource,UITableViewDelegate {
var dataList = [AnyObject]()
let identify = "homeCellId"
override init(frame: CGRect,style: UITableViewStyle) {
super.init(frame:frame,style:style)
initSubviews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func initSubviews () {
dataSource = self;
delegate = self;
registerClass(HomeCell.self,forCellReuseIdentifier: identify)
separatorStyle = .None;
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1;
}
func tableView(tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
return dataList.count;
}
func tableView(tableView: UITableView,cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(identify) as! HomeCell
cell.selectionStyle = .None;
cell.titleStr = dataList[indexPath.row] as? String
return cell
}
func tableView(tableView: UITableView,didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("the indexpath row is \(indexPath.row)")
}
func tableView(tableView: UITableView,heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 80;
}
}
二、自定义单元格(UITableViewCell)
import UIKit
class HomeCell: UITableViewCell {
//定义子视图变量
var imgView: UIImageView!
var titleLabel: UILabel!
var button: UIButton!
var titleStr: String?
// 重写单元格初始化方法
override init(style: UITableViewCellStyle,reuseIdentifier: String?) {
super.init(style: style,reuseIdentifier: reuseIdentifier)
//调用单元格初始化方法
initSubviews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:)has not been implemented")
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
//单元格子视图初始化方法
func initSubviews () {
imgView = UIImageView(frame: CGRectMake(0,0,30,30))
imgView.image = UIImage(named: "exam.png")
contentView.addSubview(imgView)
titleLabel = UILabel(frame: CGRectMake(0,frame.size.width,frame.size.height))
titleLabel.textAlignment = .Left
titleLabel.textColor = UIColor.lightGrayColor()
titleLabel.font = UIFont.systemFontOfSize(15)
titleLabel.text = "心灵鸡汤,每天一起干"
contentView.addSubview(titleLabel)
button = UIButton(type: .Custom)
button.frame = CGRectMake(0,frame.size.height)
button.setTitle("关注",forState: .Normal)
button.setTitleColor(UIColor.whiteColor(),forState: .Normal)
button.backgroundColor = UIColor.grayColor()
contentView.addSubview(button)
}
//重写单元格布局子视图方法
override func layoutSubviews() {
super.layoutSubviews()
titleLabel.text = titleStr
//...
//布局单元格子视图
//...
override func setSelected(selected: Bool,animated: Bool) {
super.setSelected(selected,animated: animated)
// Configure the view for the selected state
}
}