gpt4 book ai didi

iOS Swift,如何删除TableViewCell中的UIView并调整单元格高度?

转载 作者:行者123 更新时间:2023-11-29 05:29:22 24 4
gpt4 key购买 nike

我想动态添加或删除 TableViewCell 中的某些 View 我希望当我删除单元格中的 UIView 时,单元格高度可以调整为单元格内容高度。

下面是我的演示,我使用的是

self.frame.size.height -= 100

调整单元格高度,但效果不太好。

import UIKit
import SnapKit
class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()

let table = UITableView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 1200))
table.dataSource = self
table.delegate = self
table.estimatedRowHeight = 1
table.rowHeight = UITableView.automaticDimension
table.separatorColor = UIColor.blue
table.register(CustomCell.self, forCellReuseIdentifier: "identifierid")
view.addSubview(table)
}

}
class CustomCell:UITableViewCell {
let btn:UIButton = {
let btn = UIButton()
btn.layer.borderColor = UIColor.black.cgColor
btn.layer.borderWidth = 1
btn.setTitle("delete red view", for: .normal)
btn.setTitleColor(UIColor.black, for: .normal)
return btn
}()

let v:UIView = {
let v = UIView()
v.backgroundColor = UIColor.red
return v
}()


override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)

self.contentView.addSubview(btn)
btn.snp.makeConstraints { (make) in
make.top.equalToSuperview().offset(10)
make.size.equalTo(CGSize(width: 150,height: 50))
}
btn.addTarget(self, action: #selector(deleteCellImg), for: .touchUpInside)

self.contentView.addSubview(v)
v.snp.makeConstraints { (make) in
make.top.equalTo(btn.snp.bottom)
make.left.equalTo(btn)
make.size.equalTo(CGSize(width: 100, height: 100))
make.bottom.equalToSuperview().offset(-10)
}

}

@objc func deleteCellImg() {
v.removeFromSuperview()
self.frame.size.height -= 100 //100 is the red view height
}

required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension ViewController:UITableViewDelegate,UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 6
}


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

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
}

结果如下所示

iOS simulator screenshot

当我删除单元格中的 View 时,我不希望其他单元格高度受到影响。那么是否有一些我忽略的细节?

最佳答案

在删除 View 时调用removeFromSuperview()。这将在您的自定义单元类中完成。

然后通过table.reloadData()重新加载 TableView 。

如果行高仍然具有误导性,请使用约束或行高。

关于iOS Swift,如何删除TableViewCell中的UIView并调整单元格高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57800995/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com