How to toggle visibility with the UILabel in UITableViewCell?

99封情书 提交于 2019-12-13 20:18:37

问题


I have this chunk of code in my ViewController named PlayViewController:

words = [String]()

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cellIdentifier = "PlayTableViewCell"
    guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? PlayTableViewCell else {
        fatalError("The dequeued cell is not an instance of PlayTableViewCell.")
    }

    // Configure the cell...
    cell.wordLabel.text = words[indexPath.row]

    if (indexPath.row == 0) {
        cell.wordLabel.isHidden = false
    }

    return cell
}

And this is my code for TableViewCell named PlayTableViewCell:

import UIKit

class PlayTableViewCell: UITableViewCell {

    //MARK: Properties
    @IBOutlet weak var wordLabel: UILabel!

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

        wordLabel.lineBreakMode = .byWordWrapping;
        wordLabel.numberOfLines = 0;
        wordLabel.isHidden = true

    }

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

        // Configure the view for the selected state
    }
}

As expected, only my first wordLabel appears in my tableView. My goal is to reveal the second wordLabel when the user swipes right or left anywhere on the screen and continue this way until the user reveal the last wordLabel.

I've found how to set the swipe part (only the swipe right, behaves weirdly when the left is added) but I can't figure out how to toggle .isHidden property when I detect the gesture.

I'm not sure to be on the right path with the cell configuration but because of the placing of the wordLabel inside PlayTableViewCell, it's hard to reach it outside the function tableView.

I can index neither cell nor wordLabel and I can't figure out how could I reach the right wordLabel to toggle its visibility.


回答1:


Somewhere store property for sum of revealed labels

var numberOfRevealedLabels = 1

then every time user swipes somewhere, increase this value and then reload data of your table view (you can reload it in didSet of your variable or after you increase this value in action which is called by swiping)

numberOfRevealedLabels += 1

Now, since cells are reusable, set visibility depending on if indexPath.row is less then or equal to numberOfRevealedLabels - 1

cell.wordLabel.isHidden = !(indexPath.row <= numberOfRevealedLabels - 1)

... this also covers the case that indexPath.row is greater



来源:https://stackoverflow.com/questions/54028309/how-to-toggle-visibility-with-the-uilabel-in-uitableviewcell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!