Reputation: 1550
I'm using storyboards and a tableview. Each cell in my tableview has a UIView
in it. Is it possible to replace the IBOutlet
of this UIView
programmatically? For example doing something like this:
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
}
}
If I try to do this nothing happens.
I know many people will ask: "Why do you want to do this?". Here it goes: I am using this library VIMVideoPlayer and I create the actual player which contains a UIView in code. Instead of reusing the players I create them all at once in code and now want to display them. It really comes down to performance reasons regrading scrolling and lagging on main thread.
NOTE: I have this working in code already but really want to use storyboards. The way I have it working in code is by doing this:
videoHolderView.addSubview(customObject.videoPlayerView)
Any thoughts?
Upvotes: 2
Views: 1250
Reputation: 2071
Modifying the variable is fine, but that won't change the view hierarchy. You will need to insert the new view into the original views superview, then remove the old view. Keep in mind this will not retain any layout constraints, you will need to re-create them after adding the replacement view.
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
}
}
Upvotes: 3
Reputation: 114975
You can do this, but all your current code is doing is updating the property. You need to remove the existing view from the view hierarchy and add the new view as a sub-view.
func configureCell(with customObject: CustomObject) {
// Set the IBOutlet in code here.
self.videoPlayerView.removeFromSuperview()
self.videoPlayerView = customObject.videoPlayerView
self.addSubView(self.videoPlayerView)
}
Note that you may also have to add any constraints that are required for the new view
Upvotes: 0