在代码中替换 IBOutlet 视图

Replace IBOutlet view in code

我正在使用故事板和表格视图。我的表格视图中的每个单元格中都有一个 UIView 。是否可以通过编程方式替换此 UIViewIBOutlet?例如做这样的事情:

class CustomTableViewCell: UITableViewCell {
    @IBOutlet weak var videoPlayerView: UIView! /// Really this is a VIMVideoPLayerView (from library below) which inherits from UIView.

    func configureCell(with customObject: CustomObject) {

        // Set the IBOutlet in code here.
        self.videoPlayerView = customObject.videoPlayerView
    }
}

如果我尝试这样做,什么也不会发生。

我知道很多人会问:"Why do you want to do this?"。事情是这样的:我正在使用这个库 VIMVideoPlayer 并且我在代码中创建了包含 UIView 的实际播放器。我没有重复使用播放器,而是用代码一次创建它们,现在想显示它们。这真的归结为性能原因重新滚动和滞后于主线程。

注意:我已经在代码中使用了这个,但真的想使用故事板。我让它在代码中工作的方式是这样做的: videoHolderView.addSubview(customObject.videoPlayerView)

有什么想法吗?

您可以这样做,但是您当前的所有代码都在更新 属性。您需要从视图层次结构中删除现有视图并将新视图添加为 sub-view.

func configureCell(with customObject: CustomObject) {

    // Set the IBOutlet in code here.

    self.videoPlayerView.removeFromSuperview()

    self.videoPlayerView = customObject.videoPlayerView

    self.addSubView(self.videoPlayerView)

}

请注意,您可能还必须添加新视图所需的任何约束

修改变量没问题,但这不会改变视图层次结构。 您需要将新视图插入到原始视图超级视图中,然后删除旧视图。 请记住,这不会保留任何布局约束,您需要在添加替换视图后 re-create 它们。

class CustomTableViewCell: UITableViewCell {
    @IBOutlet weak var videoPlayerView: UIView! /// Really this is a VIMVideoPLayerView (from library below) which inherits from UIView.

    func configureCell(with customObject: CustomObject) {
        // Replace the view by inserting a new view into the same location
        // in the view hierarchy
        let newVideoPlayerView = customObject.videoPlayerView
        videoPlayerView.superview.insertSubview(newVideoPlayerView, belowSubview: videoPlayerView)
        videoPlayerView.removeFromSuperview()

        // Set the IBOutlet in code here.
        videoPlayerView = newVideoPlayerView

        // TODO: Recreate your layout constraints
    }
}