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   快乐海盗  阅读(213)  评论(0编辑  收藏  举报

编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示