一、懒加载TableView
lazy var tableView = UITableView.init(frame: UIScreen.main.bounds)
或者
lazy var tableView:UITableView = {
var myTableView = UITableView.init()
myTableView.frame = UIScreen.main.bounds
myTableView.separatorStyle = UITableViewCellSeparatorStyle.none
myTableView.delegate = self
myTableView.dataSource = self
return myTableView
}()
个人比较推荐使用第二种方法。
二、实现代理、数据源
首先让我们先加载一个数据源数组
lazy var dataArray:NSMutableArray = {
var array:NSMutableArray = NSMutableArray.init()
array.add(["title":"普通静止飞机", "controller":"NormalPlaneViewController"])
return array
}()
代理实现基本和OC一致,只是取数据的时候,挺麻烦的,因为Swift对类型很敏感
OC中的#pragma mark - XXX 在Swift中使用//MARK:XXX替代
// MARK:UITableViewDelegate&DataSources
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataArray.count;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let ID:String = "cell"
var cell:UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: ID)
if cell == nil {
cell = UITableViewCell.init(style: UITableViewCellStyle.default, reuseIdentifier: ID)
}
let dict = self.dataArray[indexPath.row] as! NSDictionary
cell?.textLabel?.text = dict["title"] as? String
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let dict = self.dataArray[indexPath.row] as! NSDictionary
let controllerName = dict["controller"] as! String
let vc = stringToViewController(controllerName: controllerName)
self.navigationController?.pushViewController(vc, animated: true)
}
/// String转Controller
///
/// - Parameter controllerName: 控制器名
/// - Returns: 控制器实例
func stringToViewController(controllerName:String) -> UIViewController{
let namespace = Bundle.main.infoDictionary!["CFBundleExecutable"] as! String
let cls:AnyClass = NSClassFromString(namespace + "." + controllerName)!
let vcCls = cls as! UIViewController.Type
let vc = vcCls.init()
return vc
}
网友评论