ios学习--tableview的使用

1.创建一个viewctrl 并继承UITableViewDelegate, UITableViewDataSource

实现方法 设置行高和数量

class JobViewCtrl: UIViewController, UITableViewDelegate, UITableViewDataSource{
    
    let homeWork = [[
        "teacherName":"阿珍老师",
        "subject":"数学",
        "introduce":"数学作业是由教师布置、学生自己独立或半独立完成的数学学习活动和内容。",
        "time":"2019-04-15",
        "finish":"49",
        "count":"50"
        ],
        ["teacherName":"阿珍老师",
          "subject":"数学",
          "introduce":"数学作业是由教师布置、学生自己独立或半独立完成的数学学习活动和内容。",
          "time":"2019-04-15",
          "finish":"49",
          "count":"50"
        ]
    ]
    // 创建几组
    func numberOfSections(in tableView: UITableView) -> Int {
        return homeWork.count
    }
    // 一组中有几个cell
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    // 设置行高
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 120
    }
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

2.初始化cell

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // 创建单元格的复用标志
        let identifier = "reusedCell"
        var cell = tableView.dequeueReusableCell(withIdentifier: identifier)
        // 判断是否可重用
        if (cell == nil) {
            // 没有重用的则创建
            cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: identifier)
        }
        // 默认标签
//        cell?.textLabel?.text = "Cell title here"
        // 默认描述标签
//        cell?.detailTextLabel?.text = "Detail info here"
        cell?.backgroundColor = UIColor.white
        // 设置选中的效果
        cell?.selectionStyle = UITableViewCellSelectionStyle.none
        
        return cell!
    }

3.cell的点击事件

这里的index 的内容是第几组的第几个cell(下标从0开始) 例如这样[0,1]

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print(indexPath)  
}

4.设置每个group之间的head和foot

这里只是添加了一个高度

// 设置 section 的 header 高度
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 20
    }
// 设置 section 的 footer 高度
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
    return 20
}

也可以自定义head和foot

    // 自定义 section 的 header
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = UIView()
        headerView.backgroundColor = UIColor.white
        return headerView
    }
    // 自定义 section 的 foot
//    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
//        let footerView = UIView()
//        footerView.backgroundColor = UIColor.white
//        return footerView
//    }

你可能感兴趣的:(iOS学习)