IOS開發儲存格自訂方法之一
第一種方法是直接寫一個繼承UITableViewCell。然後動態添加子視圖方式
具體步驟:
1.建立立一個cell類,繼承UITableViewCell
2.在這個類裡面,定義屬性,比如UILabel
3.重載建構函式,把子視圖添加上
4.可以使用這個類了。
CityCellTableViewCell類:
//// CityCellTableViewCell.swift// UITableViewDemo0//// Created by 王豐 on 7/27/15.// Copyright (c) 2015 wangfeng. All rights reserved.//import UIKitclass CityCellTableViewCell: UITableViewCell { var cityLabel:UILabel? var cityTextFiled:UITextField? var citySwitch:UISwitch? override init(style: UITableViewCellStyle,reuseIdentifier: String?){ super.init(style: style, reuseIdentifier: reuseIdentifier) //初始化子視圖,子控制項,然後添加到當前視圖 cityLabel = UILabel(frame: CGRect(x: 5, y: 5, width: 80, height: 40)) cityTextFiled = UITextField(frame: CGRect(x: 90, y: 5, width: 80, height: 40)) citySwitch = UISwitch(frame: CGRect(x: 200, y: 5, width: 80, height: 40)) //添加到當前視圖 self.addSubview(cityLabel!) self.addSubview(cityTextFiled!) self.addSubview(citySwitch!) } required init(coder aDecoder: NSCoder) { fatalError(init(coder:) has not been implemented) } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state }}
viewController重載tableView方法:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{ var cellId = mycell var cell:CityCellTableViewCell? = (tableView.dequeueReusableCellWithIdentifier(cellId) as? CityCellTableViewCell) if(cell == nil){ cell = CityCellTableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: cellId) } cell?.cityLabel?.text = cities[indexPath.row] cell?.cityTextFiled?.placeholder = input number cell?.citySwitch?.on = true return cell! }