修改子控制器中的约束

时间:2018-01-21 22:46:14

标签: ios swift xcode uiviewcontroller constraints

我有TabBarController连接到一个类class MainViewController: UIViewController的视图控制器

Storyboard

MainViewController具有以下约束作为属性:

@IBOutlet weak var ContainerBottomConstraint: NSLayoutConstraint!

以及修改约束的以下方法:

func resizeContainer() {
    ContainerBottomConstraint.constant = Constants.playingNowBarHeight
}

我想从resizeContainer()致电TabBarController现在我正试图从viewDidLoad()这样调用它

if let vc = viewControllers?[0] as? MainViewController {
        vc.resizeContainer()
}

但是我得到了 Fatal error: Unexpectedly found nil while unwrapping an Optional valueContainerBottomConstraint.constant = Constants.playingNowBarHeight

2 个答案:

答案 0 :(得分:1)

public function Hero()
{
    super();

    // If stage is available, go straight to initializer.
    // Otherwise subscribe and wait for the stage to get available.
    if (stage) onStage(null);
    else addEventListener(Event.ADDED_TO_STAGE, onStage);
}

private function onStage(e:Event):void
{
    removeEventListener(Event.ADDED_TO_STAGE, onStage);

    addEventListener(Event.ENTER_FRAME, enterFrameHandler);

    stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
    stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);

    up.visible = false;
    startMarker.visible = false;
}

如果您将约束声明为视图控制器的实例属性,则需要使@IBOutlet lazy var containerBottomConstraint = containerView.bottomAnchor.constraint(equalTo: someView.topAnchor) var 必须初始化它。只有在使用时才会读取延迟变量。

然后在视图控制器中激活它:

lazy

现在该约束是一个实例属性。

答案 1 :(得分:0)

通过向MainViewController添加属性并在TabBarController中更新属性来解决问题,然后根据viewDidLoadMainViewController中的属性值更新约束。

MainViewController

var shouldResize: Bool = false

private func initView(){
   if shouldResize {
        ContainerBottomConstraint.constant = Constants.playingNowBarHeight
    } else {
        ContainerBottomConstraint.constant = 0
    }
}

TabBarController

if let vc = viewControllers?[0] as? MainViewController {
    vc.shouldResize = true
}