首页 > 解决方案 > 自定义 UITableViewCell 中的 LayoutSubviews() 不适用于所有重用的单元格

问题描述

我尝试在 UITableView 中为单元格的编辑模式设置自定义编辑视图和动画,因此我创建了一个自定义类,将我的子视图添加到其中并在 setEditing(_:animated:) 函数中为一些帧更改设置动画。我还覆盖了 layoutSubviews() 函数,其中还提供了新的帧值:

class TableViewCell: UITableViewCell {

    override func layoutSubviews() {
        self.deleteButtonView.frame.origin.x = self.viewPosition - 80
        self.disclosureButtonView.frame.origin.x = self.contentView.bounds.width - (self.viewPosition / 2)
        self.containerView.frame.origin.x = self.viewPosition

        self.alarmImageNameView.alpha = self.viewAlpha
        self.alarmImageDateView.alpha = self.viewAlpha
        self.alarmSwitchView.alpha = self.viewAlpha

        self.deleteButton.transform = self.buttonTransform

        super.layoutSubviews()
    }

    override func setEditing(_ editing: Bool, animated: Bool) {

        self.viewPosition = editing ? 80 : 0
        self.viewAlpha = editing ? 0 : 1
        self.buttonTransform = editing ? CGAffineTransform(rotationAngle: 90 * (.pi / 180)) : .identity

        let layoutChanges = {
            self.deleteButtonView.frame.origin.x = self.viewPosition - 80
            self.disclosureButtonView.frame.origin.x = self.contentView.bounds.width - (self.viewPosition / 2)
            self.containerView.frame.origin.x = self.viewPosition

            self.alarmImageNameView.alpha = self.viewAlpha
            self.alarmImageDateView.alpha = self.viewAlpha
            self.alarmSwitchView.alpha = self.viewAlpha

            self.deleteButton.transform = self.buttonTransform
        }

        if animated {
            UIView.animate(withDuration: 0.5, delay: 0, options: [.curveEaseInOut], animations: layoutChanges, completion: nil)
        } else {
            layoutChanges()
        }

        super.setEditing(editing, animated: animated)
    }

}

它工作得很好,当我滚动时,但如果我滚动到最底部,突然self.containerView似乎忽略了 layoutSubviews() 函数提供的 frame.origin.x 值:YouTube-video of the animations

我不知道,为什么它不起作用,如果我在 layoutSubviews() 函数中设置断点,它甚至会在最后一个单元格处停止,如果我打印出self.containerView.frame.origin.x它的值也是正确的。

编辑:如果它很重要,这里是我对 cellForRowAtIndexPath 的实现:

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

    let alarmProperties = self.alarms[indexPath.row]

    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TableViewCell
    cell.delegate = self
    cell.selectionStyle = .none

    cell.alarmTimeLabel.text = "\(alarmProperties.hour):\(alarmProperties.minute)"
    cell.alarmSwitch.isOn = alarmProperties.isActive


    return cell
}

标签: iosswiftuitableviewlayoutsubviews

解决方案


推荐阅读