Swift之点击UITableView单元格动态改变cell高度

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Forever_wj/article/details/73499696

基于上一篇文章,继续需要实现点击相应的表格单元格动态改变cell的高度(上一篇文章的地址Swift之动态适配UITableView的cell高度

  • 首先需要实现UITableView的tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)协议;
  • 其次,需要一个字典记录已经点击的单元格,从而再次点击单元格刷新表格视图;
  • 改写tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell协议。
    var middleDict:Dictionary<String,String> = [:] // 记录已经点击的单元格

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell:PoemTableViewCell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath) as! PoemTableViewCell
        if cell .isEqual(nil) {
            cell = PoemTableViewCell.init(style: .default, reuseIdentifier: identifier)
        }
        cell.showLabel.text = textArray[indexPath.row] as? String
        cell.selectionStyle = .none
        // 改变showLabel的numberOfLines
        if middleDict[String(indexPath.row)] == "0" {
            cell.showLabel.numberOfLines = 0
        } else {
            cell.showLabel.numberOfLines = 1
        }
        return cell
    }

    // 实现didSelectRow
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell:PoemTableViewCell = tableView.cellForRow(at: indexPath) as! PoemTableViewCell
        if cell.showLabel.numberOfLines == 0 {
            cell.showLabel.numberOfLines = 1
            middleDict[String(indexPath.row)] = "1"
        } else {
            cell.showLabel.numberOfLines = 0
            middleDict[String(indexPath.row)] = "0"
        }
        self.myTableView.reloadData() 
    }
  • 点击cell之后,动态改变cell高度还可以添加动画效果,只需要替换self.myTableView.reloadData()为self.myTableView.beginUpdates()和self.myTableView.endUpdates();
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell:PoemTableViewCell = tableView.cellForRow(at: indexPath) as! PoemTableViewCell
        self.myTableView.beginUpdates()
        if cell.showLabel.numberOfLines == 0 {
            cell.showLabel.numberOfLines = 1
            middleDict[String(indexPath.row)] = "1"
        } else {
            cell.showLabel.numberOfLines = 0
            middleDict[String(indexPath.row)] = "0"
        }
        self.myTableView.endUpdates()
//        self.myTableView.reloadData()
    }
  • 最后再跟大家分享一个小技巧:UITableView的分割线默认是开头空15像素点,当我们需要顶格显示时,只需要重载viewDidLayoutSubviews()方法和实现tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath)即可;
override func viewDidLayoutSubviews() {
        self.myTableView.separatorInset = .zero
        self.myTableView.layoutMargins = .zero
    }

    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        cell.separatorInset = .zero
        cell.layoutMargins = .zero
    }

猜你喜欢

转载自blog.csdn.net/Forever_wj/article/details/73499696