本文介绍了Objective-C/Swift(iOS)何时在View/ViewController工作流程中应用自动约束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想弄清楚在视图设置过程中何时应用XIB上的auto-contraints设置.

I'm having some issues of figuring out when the auto-contraints setup on a XIB are applied in the view setup process.

更多说明:

  • 我为视图设置了XIB
  • 我将模拟指标"的大小设置为iPhone 3.5英寸
  • 我已经向该视图内的子视图添加了自动约束
  • 在视图控制器中,我根据viewDidLoad方法中的子视图(IBOutlet)frames/bounds执行某些操作
  • 在视图中,我根据awakeFromNib方法中的子视图(IBOutlet)frames/bounds执行某些操作
  • I've setup a XIB for a view
  • I set the "Simulated Metrics" Size to iPhone 3.5-Inch
  • I've added auto-constraints to the subviews inside this view
  • In the View Controller I perform certain operations dependent on the subview (IBOutlet) frames/bounds in the viewDidLoad method
  • In the View I perform certain operations dependent on the subview (IBOutlet) frames/bounds in the awakeFromNib method

在这两种方法(ViewController::viewDidLoad and View::awakeFromNib)中,已加载IBOutlet视图,但尚未应用约束.使用较大的模拟器(例如iPhone 6模拟器)时,实际帧仍设置为iPhone 3.5英寸(宽度320).

In those 2 methods (ViewController::viewDidLoad and View::awakeFromNib) the IBOutlet views HAVE been loaded but the constraints have no yet been applied. The actual frame is still set to the iPhone 3.5" size (width 320) when using a larger simulator (such as the iPhone 6 simulator).

何时应用这些自动约束,何时应进行需要子视图的ACTUAL框架/边界的必要操作?

When are these auto-constraints applied and when should any necessary operations that would need the ACTUAL frame/bounds of the subviews take place?

我正在使用XCode 6.3,Swift(1.2)

I'm using XCode 6.3, Swift (1.2)

推荐答案

约束在layoutSubviews方法中应用.因此,如果您想在将它们应用到UIView子类中之后做一些事情,请覆盖该方法:

The constraints are applied in the layoutSubviews method. So if you want to do something after they are applied in a UIView subclass, override the method:

   override func layoutSubviews() {
    super.layoutSubviews()
    //the frames have now their final values, after applying constraints
  }

UIViewController子类中,出于相同目的使用viewDidLayoutSubviews:

In a UIViewController subclass, use viewDidLayoutSubviews for the same purpose:

  override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    //the frames have now their final values, after applying constraints
  }

请注意,如果您向该视图添加了自动布局约束,则不应为该视图设置frame/bounds.

Please note that you shouldn't set frame / bounds for a view if you added auto layout constraints to this view.

这篇关于Objective-C/Swift(iOS)何时在View/ViewController工作流程中应用自动约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 11:48