如何在运行时增加堆栈视图特定子视图的高度? [英] How to increase height of particular subview of stack view at runtime?

查看:32
本文介绍了如何在运行时增加堆栈视图特定子视图的高度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经向垂直 UIStackView 添加了一些排列的子视图.我想通过点击某个按钮来增加一个排列好的子视图的高度.

I have added some arrangedSubViews to vertical UIStackView. and I want to increase height of one arranged subview inside on tap of some button.

尝试在子视图和主视图上添加 layoutIfNeeded.它不工作.

Tried adding layoutIfNeeded on subview and main view. Its Not working.

我正在增加子视图的高度,如下所示:

I am increasing height of subview as below :

addConstraints([self.heightAnchor.constraint(equalToConstant: 100)])
layoutIfNeeded()
sizeToFit()
layoutSubviews()

推荐答案

我认为问题在于您正在尝试向视图添加新约束,但您没有停用 heightAnchor 的现有约束.

I think the problem is that you are trying to add a new constraint to the view but you didn't deactivate the existing constraint for heightAnchor.

您可以在添加新约束之前将现有高度约束的 isActive 属性设置为 false,或者简单地将现有高度约束的常量设置为新值.

You could either set the isActive property of the existing height constraint to false before adding a new constraint or simply set the constant of the existing height constraint to a new value.

您可以为约束提供一个标识符,稍后您可以使用该标识符来获取该特定约束并更改其属性.

You can give the constraint an identifier which you can use later to get that specific constraint and change its property.

如果我是你,我会在我的代码中添加以下两个扩展:

If I were you, I would add the following two extensions to my code:

extension UIView {
    func getConstraint(withIndentifier indentifier: String) -> NSLayoutConstraint? {
        return self.constraints.filter { $0.identifier == indentifier }.first
    }
}

extension NSLayoutConstraint {
    func activate(withIdentifier identifier: String) {
        self.identifier = identifier
        self.isActive = true
    }
}

示例用法:

// When you create the constraint:
subview.heightAnchor.constraint(equalToConstant: 100).activate(withIdentifier: "THE")

// When you want to change the constant:
if let filteredConstraint = subview.getConstraint(withIndentifier: "THE") {
    filteredConstraint.constant = 500
}

如果您想要动画,只需在更改约束后立即添加以下代码:

If you want animation, just add the following code right after you changed the constraints:

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

我相信这会奏效,否则请告诉我.

I believe this will work, otherwise please let me know.

当你像这样设置约束时:

When you set the constraint like this:

self.myStackView.topAnchor.constraint(equalTo: someView.bottomAnchor , constant: 20).activate(withIdentifier: "topAnchor") 

约束实际上既不属于myStackView 也不属于someView,而是它们的超视图.虽然马特的回答是正确的,但我个人更喜欢Kh_khan 在评论中的回答:

The constraint actually belongs to neither myStackView nor someView, but their superview. Although matt's answer is correct, personally I prefer Kh_khan's answer in the comment:

self.myStackView.superView?.getConstraint(withIndentifier: "topAnchor")

让我知道它是否有效.

这篇关于如何在运行时增加堆栈视图特定子视图的高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆