Swift UITableView

UITableView

平常我们用的最多的列表展示应该就是UITableViewUITableView继承自UIScrollView,因此支持垂直滚动,而且性能极佳,加上本身的一些方法足够让我们运用到许多地方。

1、基本用法
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{
 
    var testArray = ["one","two","three","four"]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self .makeTestTableView()
        
    }
    private lazy var tableView: UITableView = {
        let testTableView = UITableView()
        testTableView.delegate = self
        testTableView.dataSource = self
        // 木有后半部分分割线的显示
        testTableView.tableFooterView = UIView()
        // 注册
        testTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "testCellIden")
        return testTableView
    }()

    
    func makeTestTableView(){
        /* 备注下,之前是2.1之前是建议不用self的,但是最近2.1又提出加self这个提案
          https://github.com/apple/swift-evolution/blob/master/proposals/0009-require-self-for-accessing-instance-members.md
          目前还是看个人习惯吧
        */
        self.tableView.frame = self.view.frame
        self.view .addSubview(self.tableView)

    }
    
   //MARK: UITableView--Delegate
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.testArray.count
    }
  
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView .dequeueReusableCellWithIdentifier("testCellIden")
        cell?.textLabel?.text = "there is \(self.testArray[indexPath.row])"
        return cell!
    }

}
2、自定义的情况

注意registerClassdequeueReusableCellWithIdentifier两个方法的不同就OK了

testTableView.registerClass(TestTableViewCell.self, forCellReuseIdentifier: "testCellIden")
let cell = tableView .dequeueReusableCellWithIdentifier("testCellIden") as! TestTableViewCell

假如是XIB

//nibName指的是我们创建的Cell文件名
let nib = UINib(nibName: "testListCell", bundle: nil)   
self.tableView.registerNib(nib, forCellReuseIdentifier: "iden")
3、要注意的地方

3-1、其他可能用到的代理方法

func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
    // 选中的情况
}

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    // 删除 或者  说编辑
    let index=indexPath.row
    self.testArray.removeAtIndex(index)
    self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Bottom)
}

3-2、当Cell 高度不定的时候

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
     //    public func boundingRectWithSize(size: CGSize, options: NSStringDrawingOptions, attributes: [String : AnyObject]?, context: NSStringDrawingContext?) -> CGRect
          return
}

UITableView需要用的太多了,继续学习中···

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容