Today, I wrote a simple tableview using SWIFT. the syntax and usage are not much different from those of OC. But pay attention to the details.
Code first
import UIKitclass ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource { var _tableView:UITableView? override func viewDidLoad() { super.viewDidLoad() _tableView=UITableView(frame: self.view.bounds, style:.Plain) self.view.addSubview(_tableView) _tableView!.delegate=self _tableView!.dataSource=self } func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int { return 20; } func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { var cell=tableView.dequeueReusableCellWithIdentifier("CellId") as? UITableViewCell if (cell==nil){ cell=UITableViewCell(style: .Default, reuseIdentifier: "CellId") } cell!.textLabel.text="\(indexPath.row)" return cell }}
Note the following:
1. Data source method,
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!
Func tableview (tableview: uitableview !, Numberofrowsinsection section: INT)-> int
These two methods must be implemented. If you do not implement these two methods, the compiler will report an error. It is no longer the same as the OC, but an error will be reported during running.
So when you finish writing _ tableview !. When datasource is set to self, an error is reported. If you work overtime in the header, uitableviewdatasource still reports an error. After you implement the above two methods, the error will disappear.
2. Cell Reuse
VaR cell = tableview. dequeuereusablecellwithidentifier ("cellid")? Uitableviewcell
Note that when the backend is strongly converted to uitableviewcell, a question mark is placed after the AS, because the cell that can be reused may not be found in the cache pool, if no question mark is displayed, the cell is nil.
Beginner's experience. If you have any questions, please kindly advise.