swift - 如何使用 UITableViewCell 中的 UILabel 切换可见性?

标签 swift uitableview uilabel toggle

我的 ViewController 中有这段代码,名为 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
}

这是我为名为 PlayTableViewCell 的 TableViewCell 编写的代码:

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
    }
}

正如预期的那样,只有我的第一个 wordLabel 出现在我的 tableView 中。 我的目标是当用户向右或向左滑动屏幕上的任意位置时显示第二个 wordLabel,并继续这种方式直到用户显示最后一个 wordLabel

我已经找到了如何设置滑动部分(只有向右滑动,添加左侧时表现怪异)但是我不知道如何在检测到时切换 .isHidden 属性手势。

我不确定单元格配置是否正确,但由于 wordLabel 位于 PlayTableViewCell 内,因此很难在函数 tableView

我既不能为 cell 也不能为 wordLabel 编制索引,而且我不知道如何找到正确的 wordLabel 来切换其可见性。

最佳答案

某处存储显示标签总和的属性

var numberOfRevealedLabels = 1

然后每次用户在某个地方滑动时,增加这个值,然后重新加载你的 TableView 的数据(你可以在变量的 didSet 中重新加载它,或者在你增加这个值之后调用滑动)

numberOfRevealedLabels += 1

现在,由于单元格是可重用的,因此根据 indexPath.row 是否小于或等于 numberOfRevealedLabels - 1

设置可见性
cell.wordLabel.isHidden = !(indexPath.row <= numberOfRevealedLabels - 1)

...这也涵盖了 indexPath.row 更大的情况

关于swift - 如何使用 UITableViewCell 中的 UILabel 切换可见性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54028309/

相关文章:

ios - 为什么我会收到错误 -[__NSArrayM length] : unrecognized selector sent to instance 0x7fd4d15211d0 while assigning data to custom tableView

ios - 当同一行被选中两次时 UITableView 崩溃

ios - UITableView 禁用单元格选择之间的突出显示

ios - 淡化 UILabel 的背景颜色? (静态展示)

ios - UITextView 中的 AttributedString 在顶部被修剪

ios - 手动添加框架 - 使用 swift 4.0 编译的模块无法在 Swift 4.0.3 中导入

ios - 在更改 SKSpriteNode 位置的同时更改 SKPhysicsBody

swift - 如何仅选择带有按钮的点击单元格?

ios - 如何让 UIViewController 弹出 Swift SWRevealViewController?

ios - 通过 CAGradientLayer 在 IOS 的 UIImageView 中添加渐变层