簡體   English   中英

UITableView滾動時如何維護UITableViewCell狀態?

[英]How to maintain UITableViewCell state when UITableView scrolling?

我有一個關於擴展UITableViewCell的問題。
當我單擊UIButton時,標題為“顯示更多”,並且正在成功擴展。
然后,當我滾動UITableView時,我看到一種情況,即我沒有單擊的其他單元格,UIButton也展開了。
我有什么好主意要解決此問題?
謝謝。

class ViewController: UIViewController {

let tableView = UITableView()
let cellWithButton = "cellWithButton"
var isExpand: Bool = false
var expandIndexs: [IndexPath] = []
let text = "If you read and listen to two articles every day, your reading and listening skills can immm If you read and listen to two articles every day, your reading and listening skills can immm If you read and listen to two articles every day, your reading and listening skills can immm If you read and listen to two articles every day, your reading and listening skills can immm If you read and listen to two articles every day, your reading and listening skills can immm"

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.delegate = self
    tableView.dataSource = self
    tableView.allowsSelection = false
    tableView.separatorInset = .zero
    tableView.estimatedRowHeight = 44
    tableView.rowHeight = UITableViewAutomaticDimension
    tableView.register(WithButtonTableViewCell.self, forCellReuseIdentifier: cellWithButton)


    self.view.addSubview(tableView)

    tableView.snp.makeConstraints { (make) in
        make.top.left.right.bottom.equalToSuperview()
    }
}

@objc func btnPressed(sender: UIButton) {

    let indexPath = IndexPath(row: sender.tag, section: 0)

    if self.isExpand == false {

        self.isExpand = true

        self.expandIndexs.append(indexPath)

    } else {
        self.isExpand = false

        let index = self.expandIndexs.index(of: indexPath)

        if let index = index {
            self.expandIndexs.remove(at: index)
        }
    }

    tableView.beginUpdates()
    tableView.reloadRows(at: [indexPath], with: .none)
    tableView.endUpdates()

}
}

extension ViewController: UITableViewDelegate, UITableViewDataSource {

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: cellWithButton, for: indexPath) as! WithButtonTableViewCell

    if self.expandIndexs.contains(indexPath) {
        cell.cellIsExpand = self.isExpand
    }
    cell.titleLabel.text = text
    cell.expandButton.addTarget(self, action: #selector(btnPressed), for: .touchUpInside)
    cell.expandButton.tag = indexPath.row
    cell.layoutIfNeeded()

    return cell
}
}


class WithButtonTableViewCell: UITableViewCell {

var cellIsExpand: Bool = false

let titleLabel: UILabel = { () -> UILabel in
    let ui = UILabel()
    ui.textColor = UIColor.black
    return ui
}()

let expandButton: UIButton = { () -> UIButton in
    let ui = UIButton()
    ui.setTitleColor(UIColor.blue, for: .normal)
    return ui
}()

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}

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

    loadUI()
    loadLayout()
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")

}

override func layoutIfNeeded() {
    super.layoutIfNeeded()

    if cellIsExpand == true {
        titleLabel.numberOfLines = 0
        expandButton.setTitle("Close.", for: .normal)
    }else{
        titleLabel.numberOfLines = 2
        expandButton.setTitle("Show More.", for: .normal)
    }
}

func loadUI() {

    self.addSubview(titleLabel)
    self.addSubview(expandButton)
}

func loadLayout() {

    titleLabel.snp.makeConstraints { (make) in
        make.top.left.equalTo(15)
        make.right.equalTo(-15)
    }

    expandButton.snp.makeConstraints { (make) in
        make.top.equalTo(titleLabel.snp.bottom).offset(10)
        make.left.equalTo(10)
        make.right.equalTo(-15)
        make.bottom.equalTo(-15)            
    }
}
}

圖片在這里

您應該為isExpand使用一個boolean數組,並在cellForRow中檢查它是否確實更改row的高度。

首先make array:

var expandingStateArray = [false,false,false,false,false,false,false,false,false,false]

然后在cellForRows中檢查每個單元格的狀態:

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: cellWithButton, for: indexPath) as! WithButtonTableViewCell

if expandingStateArray[indexPath.row] {
            titleLabel.numberOfLines = 0
            expandButton.setTitle("Close.", for: .normal)
        }else{
            titleLabel.numberOfLines = 2
            expandButton.setTitle("Show More.", for: .normal)
        }
        cell.titleLabel.text = text
        cell.expandButton.addTarget(self, action: #selector(btnPressed), for: .touchUpInside)
        cell.expandButton.tag = indexPath.row
        cell.layoutIfNeeded()


        return cell
    }
    }

在按鈕的目標方法中編寫以下代碼:

@objc func btnPressed(sender: UIButton) {

let indexPath = IndexPath(row: sender.tag, section: 0)

expandingStateArray[sender.tag] = !expandingStateArray[sender.tag]

tableView.beginUpdates()
tableView.reloadRows(at: [indexPath], with: .none)
tableView.endUpdates()

}
}

在分配/不分配cellIsExpand變量后,只需在單元格上調用layoutIfNeeded()

if self.expandIndexs.contains(indexPath) {
    cell.cellIsExpand = self.isExpand
}
cell.layoutIfNeeded()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM