IOS的UITableView控件简单使用

在IOS组件中,UITableView是几乎每个应用都会使用到的控件,没有之一。

UITableView简单使用

 var arr : [String]?

 override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.arr = ["1","2","3"]
        
        let tableView = UITableView(frame: self.view.bounds,style: UITableView.Style.plain)
        tableView.dataSource = self
        tableView.delegate = self;
        tableView.register(NSClassFromString("UITableViewCell"), forCellReuseIdentifier: "qingcheng")
        self.view.addSubview(tableView)
    }

然后实现 UITableViewDelegate,UITableViewDataSource 两个协议。

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        print("执行总条数")
        return arr!.count;
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "qingcheng",for: indexPath)
        cell.textLabel?.text = "test"
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100;
    }

点击运行

自定义cell

复杂一点的应用都会自定义一个cell来满足自己的设计需求

使用xib来实现

创建一个cocoa touch class,勾选xib

在ViewDidLoad的时候,可以需要使用UINib来加载Xib

 let tableView = UITableView(frame: self.view.bounds,style: UITableView.Style.plain)
        tableView.dataSource = self
        tableView.delegate = self;
        tableView.register(UINib.init(nibName: "MyCellTableViewCell", bundle: nil), forCellReuseIdentifier: "qingcheng")
        self.view.addSubview(tableView)

协议实现加载cell的方法也需要做对应的调整


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:MyCellTableViewCell = tableView.dequeueReusableCell(withIdentifier: "qingcheng",for: indexPath) as! MyCellTableViewCell
        cell.setName(name: "青城同学")
        return cell
    }

然后点击运行。

简单的使用差不多就到这里了。UITableView是一个非常强大的控件,比如删除cell,cell排序,机会都可以几行代码实现。

欢迎关注我的微信搜索公众号 【青城同学】,不定时和你分享一些技术和有趣的事情

posted on 2021-05-13 23:31  快乐海盗  阅读(208)  评论(0编辑  收藏  举报