Xcode - Is there a way to drag a component from on

2019-01-12 17:36发布

What I'd like to do is drag a component/view from one superview to another in Xcode's interface-builder without having its frame/position be reset.

Xcode's default behavior when doing this appears to be to center the view being moved vertically and horizontally in its new superview, while preserving its dimensions. This is extremely frustrating, as it means that the view needs to be manually repositioned in its new superview. But I had it positioned correctly before I moved it, so I'd like Xcode to just remember all attributes of its frame instead of just its width/height. Is this possible?

8条回答
叼着烟拽天下
2楼-- · 2019-01-12 18:31

This is the best solution to copy subviews to another view and retaining the positions :

  1. Select the items you want in your subview, then
  2. Editor -> Embed In -> View
  3. Copy this View (Cmd+C)
  4. Undo (Cmd+Z) (Since you just wanted the subviews)
  5. Go to the view you want the subviews in and paste it(Cmd+V)
  6. Select the Embedding View that you copy-pasted and Editor -> Unembed

Step 6 would remove the embedding view and you'll have copied just the subviews.

查看更多
唯我独甜
3楼-- · 2019-01-12 18:38

I detected another approach. It is basically: Move = Cut + Paste

This way you do:

  • get all your subviews to be children of the new parent view (P')
  • keep (almost) all of your constraints in Auto-Layout based Storyboard
  • keep your subview's relative positions (frames) one to another

This way you do not:

  • edit Storyboard file in a text editor

Base the thing is that each view except one (root) in Storyboard has its parent view. Next, when you copy/move multiple subviews, you lose frames and constraints.

The answer is pretty simple. You make a copy of your subviews (SVs) by copying their parent view (P) into new parent view (P'). This way you may need to recreate only constraints from that parent new view (P') to its new parent view but not for every subview you wanted to move.

After you did make copy of parent view (P) into new one (P'), from that new view (P') you:

  • remove all the children except ones that you wanted to move
  • recreate new parent (P') constraints
  • recreate possible Interface Builder outlets to (SVs')

And from original parent view (P) you:

  • remove all the children that you wanted to move

Before:

View1

View2

P

SVs-you-want-to-move

SVs-you-do-not-want-to-move

View3

After:

View1

View2

P

SVs-you-do-not-want-to-move

View3

P'

SVs'-you-want-to-move

I should stress that this does not generalise well if you have e.g. UIScrollView as a parent view. Then a copy of it would be again a UIScrollView what may not be desirable.

Another thing is when you do remove some of the subviews (SVs) in original parent view (P), you may need to recreate some constraints if other (non-moveable subviews) reference them. But you should do that anyway.

查看更多
登录 后发表回答