簡體   English   中英

UITableView CustomCell 復用(ImageView in CustomCell)

[英]UITableView CustomCell Reuse (ImageView in CustomCell)

我是 iOS 開發人員的新手,我對 UITableViewCell 有疑問。 我想這與出列可重用單元格有關。 我在我的自定義表格視圖單元格中添加了一個 UIImageView,還添加了一個點擊手勢來制作喜歡/不喜歡 function(圖像從空心(不喜歡)變為充滿心(喜歡)作為點擊和反轉)。 問題是當我向下滾動時,一些單元格會被自動點擊。 我發現了為什么會這樣,但仍然不知道如何適當地修復它。 以下是我的代碼,

視圖控制器

import UIKit 
struct CellData {
var title: String
var done: Bool
}

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {     
var models = [CellData]()

private let tableView: UITableView = {
    let table = UITableView()
    table.register(TableViewCell.self, forCellReuseIdentifier: TableViewCell.identifier)
    return table
}()

override func viewDidLoad() {
    super.viewDidLoad()
    view.addSubview(tableView)
    tableView.frame = view.bounds
    tableView.delegate = self
    tableView.dataSource = self
    configure()
}

private func configure() {
    self.models = Array(0...50).compactMap({
        CellData(title: "\($0)", done: false)
    })
}

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let model = models[indexPath.row]
    guard let cell = tableView.dequeueReusableCell(withIdentifier: TableViewCell.identifier, for: indexPath) as? TableViewCell else {
        return UITableViewCell()
    }
    
    cell.textLabel?.text = model.title

    return cell
}

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

    tableView.deselectRow(at: indexPath, animated: true)
    tableView.reloadData()

}
}

表格視圖單元格

import UIKit
class TableViewCell: UITableViewCell {
let mainVC = ViewController()
static let identifier = "TableViewCell"

let likeImage: UIImageView = {
    let imageView = UIImageView()
    imageView.image = UIImage(systemName: "heart")
    imageView.tintColor = .darkGray
    imageView.isUserInteractionEnabled = true
    imageView.translatesAutoresizingMaskIntoConstraints = false
    return imageView
}()


override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
    contentView.addSubview(likeImage)
    layout()
    //Tap Gesture Recognizer 실행하기
    let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didTapImageView(_:)))
    likeImage.addGestureRecognizer(tapGestureRecognizer)
    
}

required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
    super.layoutSubviews()
}
override func prepareForReuse() {
    super.prepareForReuse()
}

private func layout() {
    likeImage.widthAnchor.constraint(equalToConstant: 30).isActive = true
    likeImage.heightAnchor.constraint(equalToConstant: 30).isActive = true
    likeImage.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true
    likeImage.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -20).isActive = true
}

@objc func didTapImageView(_ sender: UITapGestureRecognizer) {        

    if likeImage.image == UIImage(systemName: "heart.fill"){
        likeImage.image = UIImage(systemName: "heart")
        likeImage.tintColor = .darkGray
        

    } else {
        likeImage.image = UIImage(systemName: "heart.fill")
        likeImage.tintColor = .systemRed

    }
    
}
}

這個 gif 顯示了它現在是如何工作的。 在此處輸入圖像描述

我嘗試使用 CellData 結構中的“完成”屬性來捕獲 uiimageview 的狀態但失敗了(不知道如何以正確的方式使用它)。 如果有人可以提供幫助,我將非常高興!

您已經發現問題出在細胞重復使用上。

當您出列要顯示的單元格時,您已經根據您的數據設置了單元格標簽的文本:

cell.textLabel?.text = model.title

需要告訴單元格是顯示空心還是填充心形圖像。

而且,當用戶點擊該圖像時,您的單元格需要告訴 controller 更新數據 model 的.done屬性。

這可以通過協議/委托模式或更常見的方式(尤其是 Swift)使用閉包來完成。

這是對您發布的代碼的快速修改......評論應該讓您對發生的事情有一個很好的了解:

struct CellData {
    var title: String
    var done: Bool
}

class ShinViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    var models = [CellData]()
    
    private let tableView: UITableView = {
        let table = UITableView()
        table.register(ShinTableViewCell.self, forCellReuseIdentifier: ShinTableViewCell.identifier)
        return table
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(tableView)
        tableView.frame = view.bounds
        tableView.delegate = self
        tableView.dataSource = self
        configure()
    }
    
    private func configure() {
        self.models = Array(0...50).compactMap({
            CellData(title: "\($0)", done: false)
        })
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return models.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: ShinTableViewCell.identifier, for: indexPath) as! ShinTableViewCell
        
        let model = models[indexPath.row]
        
        cell.myLabel.text = model.title
        
        // set the "heart" to true/false
        cell.isLiked = model.done
        
        // closure
        cell.callback = { [weak self] theCell, isLiked in
            guard let self = self,
                  let pth = self.tableView.indexPath(for: theCell)
            else { return }
            
            // update our data
            self.models[pth.row].done = isLiked
        }
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    }

}

class ShinTableViewCell: UITableViewCell {
    
    // we'll use this closure to communicate with the controller
    var callback: ((UITableViewCell, Bool) -> ())?
    
    static let identifier = "TableViewCell"
    
    let likeImageView: UIImageView = {
        let imageView = UIImageView()
        imageView.image = UIImage(systemName: "heart")
        imageView.tintColor = .darkGray
        imageView.isUserInteractionEnabled = true
        imageView.translatesAutoresizingMaskIntoConstraints = false
        return imageView
    }()
    
    let myLabel: UILabel = {
        let v = UILabel()
        v.translatesAutoresizingMaskIntoConstraints = false
        return v
    }()
    
    // we'll load the heart images once in init
    //  instead of loading them every time they change
    var likeIMG: UIImage!
    var unlikeIMG: UIImage!
    
    var isLiked: Bool = false {
        didSet {
            // update the image in the image view
            likeImageView.image = isLiked ? likeIMG : unlikeIMG
            // update the tint
            likeImageView.tintColor = isLiked ? .systemRed : .darkGray
        }
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        // make sure we load the heart images
        guard let img1 = UIImage(systemName: "heart"),
              let img2 = UIImage(systemName: "heart.fill")
        else {
            fatalError("Could not load the heart images!!!")
        }
        
        unlikeIMG = img1
        likeIMG = img2
        
        // add label and image view
        contentView.addSubview(myLabel)
        contentView.addSubview(likeImageView)

        layout()
        
        //Tap Gesture Recognizer 실행하기
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didTapImageView(_:)))
        likeImageView.addGestureRecognizer(tapGestureRecognizer)
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func layoutSubviews() {
        super.layoutSubviews()
    }
    override func prepareForReuse() {
        super.prepareForReuse()
    }
    
    private func layout() {

        // let's use the "built-in" margins guide
        let g = contentView.layoutMarginsGuide
        
        // image view bottom constraint
        let bottomConstraint = likeImageView.bottomAnchor.constraint(equalTo: g.bottomAnchor)
        // this will avoid auto-layout complaints
        bottomConstraint.priority = .required - 1
        
        NSLayoutConstraint.activate([
            
            // constrain label leading
            myLabel.leadingAnchor.constraint(equalTo: g.leadingAnchor),
            
            // center the label vertically
            myLabel.centerYAnchor.constraint(equalTo: g.centerYAnchor),
        
            // constrain image view trailing
            likeImageView.trailingAnchor.constraint(equalTo: g.trailingAnchor),
            
            // constrain image view to 30 x 30
            likeImageView.widthAnchor.constraint(equalToConstant: 30),
            likeImageView.heightAnchor.constraint(equalTo: likeImageView.widthAnchor),
            
            // constrain image view top
            likeImageView.topAnchor.constraint(equalTo: g.topAnchor),
            
            // activate image view bottom constraint
            bottomConstraint,

        ])

    }
    
    @objc func didTapImageView(_ sender: UITapGestureRecognizer) {
        
        // toggle isLiked (true/false)
        isLiked.toggle()
        
        // inform the controller, so it can update the data
        callback?(self, isLiked)
        
    }
    
}

暫無
暫無

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

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