单击Swift 4中的自定义按钮时调整单元格大小

问题描述 投票:1回答:2

我有一个视图控制器,其中我使用了表视图控制器。在我的单元格中有一个按钮,当用户单击单元格大小时应该达到550并且当再次单击时它应该回到其原始高度。我在搜索之后尝试了一些代码,但它不起作用是他们的任何解决方案对我有用吗?我的代码是这个,

var indexOfCellToExpand: Int!

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  if indexPath.row == indexOfCellToExpand {
    return 170 + expandedLabel.frame.height - 38
  }
  return 170
}
ios swift
2个回答
1
投票

使用自动布局进行展开折叠单元格,为该情况附加演示

链接:HTTPS://www.dropbox.com/s/ieltq0honml35l8/TAbleDemo.zip?dl=0.

设置单元格按钮高度约束并更新select-deselect事件上的值约束,只重新加载数据

在主视图控制器代码中

self.tblView.estimatedRowHeight = 100
self.tblView.rowHeight = UITableViewAutomaticDimension

  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "TblCell", for: indexPath) as! TblCell

        cell.btnExpandCollepse.addTarget(self, action: #selector(ViewController.expandCollapse(sender:)), for: .touchUpInside)
        return cell

    }

 @objc func expandCollapse(sender:UIButton) {

        self.tblView.reloadData()
    }

细胞类中的代码

@IBOutlet var btnExpandCollepse: UIButton!
@IBOutlet var constraintBtnHeight: NSLayoutConstraint!

@IBAction func onExpandCollepse(_ sender: UIButton) {

        sender.isSelected = !sender.isSelected

        if !sender.isSelected{

            self.constraintBtnHeight.constant = 50
        }else{
            self.constraintBtnHeight.constant = 500
        }
    }

对于约束检查下面的图像http://prntscr.com/hur8ym

使用自动调整大小单元qazxsw poi更新了标签自定义内容高度的演示

https://www.dropbox.com/s/o742kflg5yeofb8/TAbleDemo%202.zip?dl=0


© www.soinside.com 2019 - 2024. All rights reserved.