swift3.0创建自定义cell(Xib)

直接贴代码啦

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
    var tableView :UITableView?
    var itemsArray :[String]?

    func createTableView() {
        
        print("viewDidLoad\(self.view.frame)")
        
        let tableView = UITableView.init(frame: CGRect.init(x: 0, y: 0, width: screenSize().width, height: screenSize().height), style: .plain);
        
        tableView.delegate = self
        tableView.dataSource = self
        self.view.addSubview(tableView)
        
        let headerView :TableViewHeaderView = TableViewHeaderView.loadNibView()
        
        tableView.tableHeaderView = headerView
        
        tableView.tableFooterView = UIView.init()
        //xib画的cell使用此方法会不显示,不知为何??
//        tableView.register(CustomTableViewCell.self, forCellReuseIdentifier: "lll")
        
        tableView.register(UINib.init(nibName: "CustomTableViewCell", bundle: nil), forCellReuseIdentifier: "lll")
        
    }
      //代理方法实现
    func numberOfSections(in tableView: UITableView) -> Int {
        
        return 1
    }
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return itemsArray!.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return 44
    }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        //原生cell
//        let cell :UITableViewCell = UITableViewCell.init(style: UITableViewCellStyle.subtitle, reuseIdentifier: "tableViewCell")
//        cell.textLabel?.text = "Row # \(itemsArray![indexPath.row])"
        
        //自定义cell
        let identify = "lll"
//        let cell:CustomTableViewCell = CustomTableViewCell.init(style: UITableViewCellStyle.subtitle, reuseIdentifier: identify) as! CustomTableViewCell
        let cell:CustomTableViewCell = tableView.dequeueReusableCell(withIdentifier: identify) as! CustomTableViewCell
        
        
        cell.name = "第\(indexPath.row)行疯了~"
        
        return cell
    }
    
    //选中某行
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        NSLog("点击第\(indexPath.row)个cell");
    }
    
    //删除一行
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        let index = indexPath.row as Int
        itemsArray!.remove(at: index)
        
        self.tableView?.deleteRows(at: [indexPath], with: UITableViewRowAnimation.fade)
        //也可以直接用.枚举
    }
}

至于为什么使用方法 open func register(_ cellClass: Swift.AnyClass?, forCellReuseIdentifier identifier: String) 不显示cell,暂时还不明白。。希望有同学可以指点一下,感激不尽!

你可能感兴趣的:(swift3.0创建自定义cell(Xib))