本文介绍了heightAnchor.constraint不会更改视图高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码:

func show(){
    view.translatesAutoresizingMaskIntoConstraints = false
    view.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0).isActive = true
    view.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true
    view.heightAnchor.constraint(equalToConstant: view.frame.height - 300).isActive = true
    view.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0).isActive = true
}

func hide(){
    view.translatesAutoresizingMaskIntoConstraints = false
    view.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0).isActive = true
    view.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true
    view.heightAnchor.constraint(equalToConstant: view.frame.height + 300).isActive = true
    view.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0).isActive = true
}

show功能正常,但hide功能不起作用,heightAnchor不起作用.

show function works fine, but hide function does not work and heightAnchor does not work.

推荐答案

首先声明约束

var heightArchonWhenShow = view.heightAnchor.constraint(equalToConstant: view.frame.height - 300)
var heightArchonWhenHide = view.heightAnchor.constraint(equalToConstant: view.frame.height + 300)

初始化对ViewDidLoad的约束

After init your constraints on ViewDidLoad

func setConstraints(){
    view.translatesAutoresizingMaskIntoConstraints = false
    view.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0).isActive = true
    view.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true
    view.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0).isActive = true
    heightArchonWhenShow.isActive = true
}

简单激活它们,不要覆盖.像这样:

And simple active them , don't overwrite. Like this:

func show(){
    heightArchonWhenShow.isActive = true
    heightArchonWhenHide.isActive = false
}

func hide(){
    heightArchonWhenShow.isActive = false
    heightArchonWhenHide.isActive = true
}

如果您愿意,您还可以为更改设置动画:

If u want u can also animate changes, like that :

func hide(){
    heightArchonWhenShow.isActive = false
    heightArchonWhenHide.isActive = true

    UIView.animate(withDuration: 0.3) {
        self.view.layoutIfNeeded()
    }
}

这篇关于heightAnchor.constraint不会更改视图高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 19:02