Reputation: 315
I have a UIButton which the user can drag and drop. I recognize the drag and drop with the following method:
func addTarget(_ target: AnyObject?,
action action: Selector, forControlEvents controlEvents: UIControlEvents)
In addition, I have a view. Both the view and UIButton are siblings, and are defined in the IB.
My goal is that when the user drags the button into the view, then the button will be disconnected from it's parent, and its new parent will be the view. In other words, the button will be a subview of the view.
What I am doing is (when the button is dragged into the view):
button.removeFromSuperview()
view.addSubview(button)
This indeed removes the button from it's parent, but still I dont see it inside the view. So, I tried giving the button a red background, and now when the button is dragged to the view, I can see some wierd small red background at the simulator top left corner.
Can someone tell me please what am I doing wrong? Missing somehting?
Upvotes: 1
Views: 1004
Reputation: 404
to remove a button from superview
button.removefromsuperview()
to add it on a view
view.addsubview(button)
Upvotes: 0
Reputation: 96
If you change the parent of any object, its frame remain same as it was in its old parent.
So, If the frame of the new parent is different than old parent than you need to set the frame of your object according to the new parent.
To change the parent you can just add the object in to new parent, no need to remove the object from its old parent (object removeFromSuperview), it will manage automatically, because one object can exist at in one parent at the same time.
Upvotes: 0
Reputation: 20379
Daniel Rahamim,
I believe the button is getting added to your view but because button's frame is still pointing to the outer space (beyond child views frame) you cant see it. Try setting the frame and lemme know if you can see it :)
button.removeFromSuperview()
button.frame = CGRectMake(view.center.x, view.center.y, button.frame.size.width, button.frame.size.height)
view.addSubview(button)
Upvotes: 1