显示隐藏 UILabel 过度约束不能按预期的高度约束工作

问题描述 投票:0回答:3

我有

UILabel
,我在
tapGesture
上显示和隐藏。 我以编程方式创建标签并仅以编程方式设置约束。

默认情况下 UILabel 是可见的

heightConstraint = 230
在 tapGesture 方法上,我正在正确制作
heightConstraint = 0
及其隐藏标签。 再次在 tapGesture 上我需要显示标签, 所以当我再次点击时,我可以再次看到
heightConstraint = 230
,但是在 UI 中看不到标签。

可能有什么问题,只有隐藏有效而显示无效。

以下是我设置高度限制的 tapGesture 方法的代码。

@objc func tapLabel(gesture: UITapGestureRecognizer) {
        print("tap working")
        isExpanded.toggle()
        if(isExpanded){
            NSLayoutConstraint.activate([
                reminderBulletsLbl.heightAnchor.constraint(equalToConstant: 230)
            ])
        }else{
            NSLayoutConstraint.activate([
                reminderBulletsLbl.heightAnchor.constraint(equalToConstant: 0)
            ])
        }
    }

我试图停用约束但没有工作。

请找到附件中的屏幕截图。

  1. 看到标签时的默认状态

  1. 点击时,当标签被隐藏时。

现在再次点击后标签不显示了。

提前致谢。

ios swift xcode constraints uilabel
3个回答
0
投票

此行为将在您单击时添加更多约束

if(isExpanded){
    NSLayoutConstraint.activate([
        reminderBulletsLbl.heightAnchor.constraint(equalToConstant: 230)
    ])
} else {
    NSLayoutConstraint.activate([
       reminderBulletsLbl.heightAnchor.constraint(equalToConstant: 0)
    ])
}

而且会造成他们价值观的冲突,你需要

var heightCon:NSLayoutConstraint!

和里面

viewDidLoad
设置初始状态

heightCon = reminderBulletsLbl.heightAnchor.constraint(equalToConstant: 230)
heightCon.isActive = true

然后在点击动作中使用常量属性

heightCon.constant = isExpanded ? 230 : 0
view.layoutIfNeeded()

-1
投票

首先你需要保留一个高度约束的实例,不要每次都创建新的高度约束。像这样

var constraint: NSLayoutConstraint?

在 viewDidLoad 里面添加这个

constraint = label.heightAnchor.constraint(equalToConstant: 250)
constraint?.isActive = true

然后在 tapLabel 函数中添加

constraint?.constant = isExpanded ? 20 : 250

第二 最重要的是当你把你的高度设置为 0 时,你不能再点击它了,因为标签高度为零,那么如果你将它设置为 20,你将如何点击高度为零的东西,就像我提供的示例一样,标签将是clickable 如果你想完全隐藏标签也许你需要采取另一种方法而不是点击标签


-1
投票

我刚刚解决了这个问题。 问题是我在声明 var heightCon:NSLayoutConstraint! 作为本地人。

我只是在全局中声明相同。

以下是解决问题的代码。

var heightCon:NSLayoutConstraint!
    @objc func tapLabel(gesture: UITapGestureRecognizer) {
        isExpanded.toggle()
        if let constraint = heightCon{
            constraint.isActive = false
        }
        heightCon = reminderBulletsLbl.heightAnchor.constraint(equalToConstant: isExpanded ? 230 : 0)
        heightCon.isActive = true
    }

感谢@Sh_Khan 的帮助。

© www.soinside.com 2019 - 2024. All rights reserved.