简体   繁体   English

iOS-从XIB文件引用和以编程方式移动视图

[英]iOS - referencing and programmatically moving a view from an XIB file

I'm using Xcode 8 and working on a legacy .xib file and need to figure out how to programmatically move all the objects. 我正在使用Xcode 8并处理旧版.xib文件,需要弄清楚如何以编程方式移动所有对象。 Questions: 问题:

  1. How can I programmatically reference the view (pointed to by the red arrow)? 如何以编程方式引用视图(由红色箭头指向)?
  2. Assuming I can reference the view, would programmatically moving it also relatively move the four buttons and label contained within it? 假设我可以引用该视图,以编程方式移动它还会相对移动其中包含的四个按钮和标签吗?

Here's a screen shot of the View hierarchy of the .xib file: 这是.xib文件的View层次结构的屏幕截图:

在此处输入图片说明

Normally, I would just create a UIView object in a separate .xib file with the contents of the view from question #1, and add it the .xib file referenced above but this is existing code and I want to minimize changes if possible. 通常,我只是在一个单独的.xib文件中创建一个UIView对象,其中包含问题#1的视图内容,并将其添加到上面引用的.xib文件中,但这是现有代码,并且我希望尽可能减少更改。

Assuming you have a view controller for this story board, Option+click your source file to open it in the assistant editor. 假设您有一个故事板的视图控制器,请按住Option键并单击您的源文件以在助手编辑器中将其打开。 You CTRL+Drag from the document outline (where your arrow is pointing) to the spot in your source file where you want the outlet to appear and Xcode will create an IBOutlet for the view. 您从文档轮廓(箭头指向的位置)中按CTRL +拖动到源文件中要显示插座的位置,Xcode将为视图创建IBOutlet。

If your question is can you load just the view from the story board without the view controller. 如果您的问题是仅从故事板上加载视图,而无需使用视图控制器。 I suppose you could instantiate the view controller, take a strong reference to the view, remove the view from its superview and then trash the viewcontroller, but that seems a bit wasteful; 我想您可以实例化视图控制器,对视图进行强引用,从其超级视图中删除视图,然后废弃视图控制器,但这似乎有点浪费; in this instance I would copy and paste the view into its own nib. 在这种情况下,我将视图复制并粘贴到其自己的笔尖中。

Note that as far as moving the view, yes it will move all of its subviews. 请注意,就移动视图而言,是的,它将移动其所有子视图。 If this is a temporary animation kind of thing consider using the .transform property along with one of the UIView Animation methods. 如果这是一种临时动画,请考虑将.transform属性与UIView Animation方法之一一起使用。 You can also CTRL+Drag the constraints from interface builder and manipulate the constraints in code. 您也可以从界面构建器中CTRL + Drag约束,并在代码中操作约束。 You should avoid setting the frame/center manually if you are using constraints otherwise autolayout will be fighting with you. 如果您使用约束,则应避免手动设置框架/中心,否则自动布局会给您带来麻烦。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM