Swift語言中的UITableView中着實很坑爹,爲什麼呢,因爲在遵循協議後經常會報這樣的錯誤:does not conform to protocol 'UITableViewDataSource'。而且是第一次嘗試的夥伴們經常會發現,我寫的代碼沒有問題呀,該寫的都寫了,爲什麼還是報錯呢,有的時候是xcode的問題,有的時候又是自己遵循的協議中有必需實現的方法而沒有實現導致的。所以遇到這種問題,大家不妨跳進代理中去看看必須實現的方法都實現的沒有。
下面是我寫的一個小demo,大家可以看看。
import UIKit
var dataArray: NSMutableArray?
var tableView: UITableView?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = UIColor.orangeColor()
self.navigationItem.title = "您好 Swift"
self.dataArray = NSMutableArray()
self.dataArray!.addObject("您好 Swift")
self.dataArray!.addObject("您好 Swift")
self.dataArray!.addObject("您好 Swift")
self.dataArray!.addObject("您好 Swift")
self.dataArray!.addObject("您好 Swift")
self.dataArray!.addObject("您好 Swift")
self.dataArray!.addObject("您好 Swift")
self.dataArray!.addObject("您好 Swift")
self.dataArray!.addObject("您好 Swift")
self.dataArray!.addObject("您好 Swift")
self.dataArray!.addObject("您好 Swift")
self.dataArray!.addObject("您好 Swift")
self.dataArray!.addObject("您好 Swift")
self.dataArray!.addObject("您好 Swift")
self.dataArray!.addObject("您好 Swift")
self.dataArray!.addObject("您好 Swift")
self.dataArray!.addObject("您好 Swift")
self.dataArray!.addObject("您好 Swift")
self.dataArray!.addObject("您好 Swift")
self.dataArray!.addObject("您好 Swift")
NSLog("%@", self.dataArray!)
self.tableView = UITableView(frame: self.view.frame, style:UITableViewStyle.Plain)
self.tableView!.delegate = self
self.tableView!.dataSource = self
self.tableView!.registerClass(UITableViewCell.self, forCellReuseIdentifier: "MyTestCell")
self.view.addSubview(self.tableView!)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return self.dataArray!.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "MyTestCell")
var string :String = self.dataArray?.objectAtIndex(indexPath.row)as String
cell.textLabel.text = string
cell.textLabel.text = string
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
tableView.deselectRowAtIndexPath(indexPath, animated: true)
var controller = secondViewController()
controller.title = "Swift 的自我介紹"
controller.view.backgroundColor = UIColor(red: 10/255.0, green: 100/255.0, blue: 200/255.0, alpha: 1.0)
self.navigationController?.pushViewController(controller, animated: true)
}
}