iOS之UITableviewCell的自定义方法

目前个人总结三种方法

一.使用storyboard自定义UITableViewCell

在Storyboard的相应的界面拖入TableView,并拖入UItableViewCell到TableView上


设置tableView的Identifier,用于cell的复用,并设置于该cell相关联的class




创建关联的cell文件,并与prototype cell创建关联

class ShopCartCell:UITableViewCell  {

//storyboard 方式

required init?(coder aDecoder: NSCoder) {

//fatalError("init(coder:) has not been implemented")

super.init(coder: aDecoder)

}

override func awakeFromNib() {

super.awakeFromNib()

// Initialization code

}

@IBOutlet weak var iconView: UIImageView!

@IBOutlet weak var titleLable: UILabel!

}

在tableView的数据源代理中使用cell


func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

var cell = tableView.dequeueReusableCellWithIdentifier("shopcartcell",forIndexPath: indexPath) as! ShopCartCell

cell.iconView.sd_setImageWithURL(NSURL(string: "http://pic7.nipic.com/20100517/3409334_180613088650_2.jpg"))

return cell

}

二,使用xib方式

使用xib方式和使用storyboard方式基本一样,首先创建xib文件,并设置相应的class,创建关联控件

不同点是使用xib需要在tableview中注册复用的lib

如下

tableview.registerNib(UINib(nibName: "ShopCartCell", bundle: NSBundle(forClass:ShopCartCell2.self)), forCellReuseIdentifier: "shopcartcell")

三,使用代码方式

1,创建自定义cell,继承UITableViewCell

class ShopCartCell: UITableViewCell {

//代码方式

var iconView:UIImageView!

override init(style: UITableViewCellStyle, reuseIdentifier: String?) {

super.init(style: style, reuseIdentifier: reuseIdentifier)

selectionStyle = UITableViewCellSelectionStyle.None

iconView=UIImageView(frame: CGRectMake(0, 0, self.frame.width/4, 86))

contentView.addSubview(iconView)//必须添加到contentView中

}

required init?(coder aDecoder: NSCoder) {

fatalError("init(coder:) has not been implemented")

}

}

2.在TableView中注册cell,用于复用

tableview.registerClass(ShopCartCell3.self, forCellReuseIdentifier: "shopcartcell")

3.在代理中使用cell

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

var cell = tableView.dequeueReusableCellWithIdentifier("shopcartcell",forIndexPath: indexPath) as! ShopCartCell

cell.iconView.sd_setImageWithURL(NSURL(string: "http://pic7.nipic.com/20100517/3409334_180613088650_2.jpg"))

return cell

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容