Reputation: 565
I am working on an iPhone application using Swift 4 which creates characters.
About this application: on the Storyboard I created some UIImageViews that render on top of each other which represent some parts of the character such as socks, shoes, pants, shirts. I then combine all these layers in the code to create the full character. I have buttons in the user interface to choose a category. When a category is chosen, I display all possible items the character can wear in a UICollectionView. The user then selects an item from this collection and so the corresponding image changes accordingly.
The problem: since I have created these UIImageViews on top of each other using the Storyboard already, they already have an order while rendering. But sometimes the items have to render in a different order. For example, sometimes shoes have to render on top of pants as in wearing a skinny jeans, while other times shoes have to render under the pants as in wearing a bootcut jeans. Sometimes the user doesn't want to bring a layer all the way to the top but between some certain layers.
I want to give the users the ability to change the render order of items or move them a layer up or down.
What would be a good approach to solve this problem?
Thanks in advance for the answers.
Upvotes: 0
Views: 457
Reputation: 17722
A UIView renders it child views from first to last. Thus the rear subviews cover the front subviews. There are several methods to change the order of subviews. You may use bringSubview(toFront:)
.
view.bringSubview(toFront: shoeView)
Will render the subview shoeView
at last such that is on top of all other subviews of view
.
If you want to move a view, you might use insertSubview(_:at:)
. If the view always a subview, it is simply moved to the new index.
Upvotes: 1
Reputation: 19765
You will have to do it programmatically, and I think the best way is to keep @IBOutlet
s to those UIImageView
s and then at the appropriate time just switch their order in their superview.subviews
- the view uses the order of it's subviews to determine the order of rendering them.
So just to illustrate a short example:
@IBOutlet var shoesImageView: UIImageView!
@IBOutlet var pantsImageView: UIImageView!
@IBAction func putShoesOnTop() {
let superView = shoesImageView.superview!
superView.bringSubview(toFront: shoesImageView)
}
@IBAction func putPantsOnTop() {
let superView = pantsImageView.superview!
superView.bringSubview(toFront: pantsImageView)
}
Upvotes: 0