簡體   English   中英

在代碼中替換IBOutlet視圖

[英]Replace IBOutlet view in code

我正在使用故事板和桌面視圖。 我的tableview中的每個單元格都有一個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
    }
}

如果我嘗試這樣做沒有任何反應。

我知道很多人會問:“你為什么要這樣做?” 在這里:我使用這個庫VIMVideoPlayer ,我創建了包含代碼中的UIView的實際播放器。 我沒有重復使用播放器,而是在代碼中一次創建它們,現在想要顯示它們。 這真的歸結為在主線程上重新滾動和滯后的性能原因。

注意:我已經在代碼中工作,但我真的想使用故事板。 我在代碼中工作的方式是這樣做: videoHolderView.addSubview(customObject.videoPlayerView)

有什么想法嗎?

修改變量很好,但這不會改變視圖層次結構。 您需要將新視圖插入到原始視圖superview中,然后刪除舊視圖。 請記住,這不會保留任何布局約束,您需要在添加替換視圖后重新創建它們。

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

您可以這樣做,但您當前的所有代碼都在更新屬性。 您需要從視圖層次結構中刪除現有視圖,並將新視圖添加為子視圖。

func configureCell(with customObject: CustomObject) {

    // Set the IBOutlet in code here.

    self.videoPlayerView.removeFromSuperview()

    self.videoPlayerView = customObject.videoPlayerView

    self.addSubView(self.videoPlayerView)

}

請注意,您可能還必須添加新視圖所需的任何約束

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM