美文网首页
Swift - 使用表格组件(UITableView)实现分组列

Swift - 使用表格组件(UITableView)实现分组列

作者: 小驴拉磨 | 来源:发表于2020-06-19 17:44 被阅读0次

    1、样例说明:
    (1)列表以分组的形式展示
    (2)同时还自定义分区的头部和尾部
    (3)点击列表项会弹出消息框显示该项信息。


    image.png

    代码:

    import UIKit
    
    class TableViewViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
        
        var ctrlnames: Dictionary<Int, [String]>?
        var tableView: UITableView?
        var adHeaders:[String]?
    
        override func viewDidLoad() {
            super.viewDidLoad()
            
            setupUI()
            
        }
    
        
        func setupUI()
        {
            //初始化数据,这一次数据,我们放在属性列表文件里
            self.ctrlnames = [
                0:[String]([
                    "UILabel 标签",
                    "UITextField 文本框",
                    "UIButton 按钮"]),
                1:[String]([
                    "UIDatePiker 日期选择器",
                    "UIToolbar 工具条",
                    "UITableView 表格视图"])
            ];
             
            print(self.ctrlnames as Any)
            
            adHeaders = [
                "常见 UIKit 控件",
                "高级 UIKit 控件"
            ]
             
            //创建表视图
            self.tableView = UITableView(frame: self.view.frame, style:.plain)
            self.tableView!.delegate = self
            self.tableView!.dataSource = self
            //创建一个重用的单元格
            self.tableView!.register(UITableViewCell.self,
                                     forCellReuseIdentifier: "SwiftCell")
            self.view.addSubview(self.tableView!)
             
            //创建表头标签
            let frame = CGRect(x:0, y:0, width:self.view.bounds.size.width, height:30)
            let headerLabel = UILabel(frame: frame)
            headerLabel.backgroundColor = UIColor.black
            headerLabel.textColor = UIColor.white
            headerLabel.numberOfLines = 0
            headerLabel.lineBreakMode = .byWordWrapping
            headerLabel.text = "常见 UIKit 控件"
            headerLabel.font = UIFont.italicSystemFont(ofSize: 20)
            self.tableView!.tableHeaderView = headerLabel
        }
    
    }
    
    // MARK: UITableViewDelegate & UITableViewDataSource
    extension TableViewViewController
    {
        //在本例中,只有一个分区
        func numberOfSections(in tableView: UITableView) -> Int {
            return adHeaders?.count ?? 0
        }
         
        //返回表格行数(也就是返回控件数)
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            let ctrlname = self.ctrlnames?[section]
            return ctrlname?.count ?? 0
        }
         
        //创建各单元显示内容(创建参数indexPath指定的单元)
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)
            -> UITableViewCell {
            //为了提供表格显示性能,已创建完成的单元需重复使用
            let identify:String = "SwiftCell"
            //同一形式的单元格重复使用,在声明时已注册
            let cell = tableView.dequeueReusableCell(withIdentifier: identify,
                                                     for: indexPath)
            cell.accessoryType = .disclosureIndicator
            let ctrlname = self.ctrlnames?[indexPath.section]
            cell.textLabel?.text = ctrlname![indexPath.row]
            return cell
        }
        
        // UITableViewDataSource协议中的方法,该方法的返回值决定指定分区的头部
        func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int)
            -> String? {
            return self.adHeaders?[section]
        }
         
        // UITableViewDelegate 方法,处理列表项的选中事件
        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            self.tableView!.deselectRow(at: indexPath, animated: true)
             let ctrlname = self.ctrlnames?[indexPath.section]
            let itemString = ctrlname![indexPath.row]
             
            let alertController = UIAlertController(title: "提示!",
                                    message: "你选中了【\(itemString)】", preferredStyle: .alert)
            let okAction = UIAlertAction(title: "确定", style: .default,handler: nil)
            alertController.addAction(okAction)
            self.present(alertController, animated: true, completion: nil)
        }
         
        //滑动删除必须实现的方法
        func tableView(_ tableView: UITableView,
                       commit editingStyle: UITableViewCell.EditingStyle,
                       forRowAt indexPath: IndexPath) {
            print("删除\(indexPath.row)")
            let index = indexPath.row
            var ctrlname = self.ctrlnames?[indexPath.section]
            ctrlname?.remove(at: index)
            self.tableView?.deleteRows(at: [indexPath],
                                       with: .top)
        }
         
        //滑动删除
        func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath)
            -> UITableViewCell.EditingStyle {
                return UITableViewCell.EditingStyle.delete
        }
         
        //修改删除按钮的文字
        func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt
            indexPath: IndexPath) -> String? {
            return "删除"
        }
    }
    
    

    跟一组的主要区别:

    // 返回分组数
    func numberOfSections(in tableView: UITableView) -> Int {
      return adHeaders?.count ?? 0
    }
     
    // UITableViewDataSource协议中的方法,该方法的返回值决定指定分区的头部
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int)
        -> String? {
        return self.adHeaders?[section]
    }
    

    原文出自:www.hangge.com 转载请保留原文链接:https://www.hangge.com/blog/cache/detail_557.html

    相关文章

      网友评论

          本文标题:Swift - 使用表格组件(UITableView)实现分组列

          本文链接:https://www.haomeiwen.com/subject/suhbxktx.html