将单元格的子视图移到前面 swift

Move subview of a cell to the front swift

我有一个带有按钮的单元格。当我按下按钮时,我开始播放动画,表示正在准备一些东西。我在 @IBAction 函数中这样做:(这是在我的自定义 tableViewCell 函数中)。

@IBAction func playNowTapped(_ sender: UIButton) {
    let loadingShape = CAShapeLayer()
    //Some animating of the shape
}

我在 @IBAction 中定义了这个形状,因为如果我再次按下按钮,这个过程应该重复

但是,因为在 tableView 的 cellForRowAt 函数中只有显示在设备上的必要单元格被加载到一个块中,所以如果我在加载动画时向下滚动,我的动画每隔几个单元格就会重复一次。

到目前为止我所做的是通过定义一个函数并在按钮的 @IBAction 函数中调用它来附加到我之前按下的所有按钮的列表中,如下所示:

func findCell() {
    //Iterate tableView list and compare to current cellText
    for value in list {
        if value == cellText.text {
             //If found, checking if value is already stored in pressedBefore
             for selected in pressedBefore {
                 if selected == value { return }
             }
             alreadyPlay.append(song: cellText.text!)
        }
    }
}

然后,在我的cellForRowAt函数中,我只是做了一个反向操作,检查列表中的当前索引是否与已选择的索引中的任何值相同。

这些都过滤掉后,我现在只有一个未选中的列表ones.However,我现在不知道该怎么办了。

奇怪的是,cell.bringSubview(tofront: cell.cellText) cell.bringSubview(tofront: cell.buttonText) 并没有改变子视图的顺序。我现在该怎么办?难不成CAShapeLayer()不认为是子视图,而只是一层?

提前致谢!

很奇怪,cell.bringSubview(前面:cell.cellText) cell.bringSubview(tofront: cell.buttonText) 不会改变子视图的顺序。我现在该怎么办?

bringSubview(tofront:) 仅适用于直接子视图。传统上,您的 cellText 和 buttonText 是 cell.contentView.

的子视图

所以试试

cell.contentView.bringSubview(tofront: cell.buttonText)

有没有可能CAShapeLayer()不被认为是子视图,而是 只有一层?

是的,CAShapeLayer 继承自 CALayer,仅被视为其视图的图层,可能需要通过 layoutSubviews() or draw()

进行更新

看到那些嵌套的 for 循环和 if 语句,我想我会提供一种方法来稍微清理一下。

func findCell() {
    //find list elements that match cell's text and ensure it hasn't been pressed before
    list.filter { [=11=] == cellText.text && !pressedBefore.contains([=11=]) }.forEach {
        alreadyPlay.append(alreadyPlayed(song: LeLabelOne.text!, artist: leLabelThree.text!))
    }
}

// alternative using Sets
func findCell() {
    let cellTextSet = Set(list).intersection([cellText.text])

    // find entries in cellTextSet that haven't been pressed before
    cellTextSet.subtract(Set(pressedBefore)).forEach {
        alreadyPlay.append(alreadyPlayed(song: LeLabelOne.text!, artist: leLabelThree.text!))
    }
}