我需要在UITableView中加载自定义单元格.我创建了一个名为“CustomTableViewCell”的UITableViewCell的自定义子类.我已经在桌面视图中添加了一个UITabelViewCell(使用拖放),如图所示.然后在文件检查器中,我将该UITabelViewCell的类设置为“CustomTableViewCell”.这是我的代码:
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource { @IBOutlet var tableView : UITableView var items = String[]() override func viewDidLoad() { super.viewDidLoad() items = ["Hi","Hello","How"] self.tableView.registerClass(CustomTableViewCell.self,forCellReuseIdentifier: "CusTomCell") // Do any additional setup after loading the view,typically from a nib. } func tableView(tableView: UITableView!,numberOfRowsInSection section: Int) -> Int{ return items.count } func tableView(tableView: UITableView!,cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!{ var cell:CustomTableViewCell? = self.tableView.dequeueReusableCellWithIdentifier("CusTomCell") as? CustomTableViewCell if !cell { cell = CustomTableViewCell(style: UITableViewCellStyle.Subtitle,reuseIdentifier: "CusTomCell") } println("cell \(cell)") // cell.?.labelTitle.text = items[indexPath.row] cell!.labelTitle.text = "some text" return cell } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
解决方法
嗨最后我找到了我的问题的解决方案..请检查我的代码……对我有用..
class ViewController: UIViewController,UITableViewDataSource { @IBOutlet var tableView : UITableView var items = String[]() override func viewDidLoad() { super.viewDidLoad() items = ["Hi","How"] // Do any additional setup after loading the view,numberOfRowsInSection section: Int) -> Int{ return items.count } func tableView(tableView: UITableView!,cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!{ var cell:CustomTableViewCell? = self.tableView.dequeueReusableCellWithIdentifier("CusTomCell",forIndexPath: indexPath) as? CustomTableViewCell cell!.labelTitle.text = "some text" return cell } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }