【问题标题】:Trying to resize an UIView when text in a label is hidden隐藏标签中的文本时尝试调整 UIView 的大小
【发布时间】:2020-09-30 07:32:10
【问题描述】:

@IBOutlet weak var CompanyDetailsBottom: NSLayoutConstraint!
    @IBOutlet weak var CompanyDetailsView: UIView!
    @IBAction func toggleCollapisbleView(_ sender: UIButton) {
        
        if(CompanyDetailsView.isHidden){
            var _CompanyHeight: CGFloat {
                get {
                   return CompanyDetailsBottom.constant.magnitude
                }
                set {
                    CompanyDetailsBottom.constant.magnitude = 0
                }
            }
            CompanyDetailsView.isHidden = false
        }else {
            CompanyDetailsView.isHidden = true
        }
    }
    
}

如果标签被隐藏,我正在尝试调整视图的大小,但出现无法分配给属性:“幅度”是一个仅获取属性的错误。

【问题讨论】:

  • 您好 Daniel,如果您更清楚地格式化代码 sn-p,它将帮助其他人回答您的问题。最后似乎有一个流浪},第一行的缩进比其他行少,这使得其余部分看起来像是第一个声明的一部分。我对NSLayoutConstraint 不熟悉,但您是否尝试直接运行CompanyDetailsBottom.constant.magnitude = 0 而不是将它放在这样的计算变量的设置器中?

标签: swift uiview


【解决方案1】:

如果你不想使用约束,你可以做的是将你的CompanyDetailsView 嵌入到一个垂直的UIStackView 中,然后当你隐藏它时,堆栈视图的高度将自动为 0。

UILabel 是否嵌入在 UIView 中?如果是这样,您可以将 UIView 更改为 UIStackView,这样如果标签隐藏,高度将为 0

【讨论】:

  • 将其嵌入 UIStackView 效果非常好!非常感谢
【解决方案2】:

您可以使用下面的扩展来隐藏视图,其父级将调整其高度

extension UIView {

    var isGone: Bool {
        get {
            return isHidden
        }
        set {
            let constraints = self.constraints.filter({ $0.firstAttribute == .height && $0.constant == 0 && $0.secondItem == nil && ($0.firstItem as? UIView) == self })
            self.isHidden = newValue

            if newValue {
                if let constraint = constraints.first {
                    constraint.isActive = true
                } else {
                    let constraint = NSLayoutConstraint(item: self, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 0)
                    // constraint.priority = UILayoutPriority(rawValue: 999)
                    self.addConstraint(constraint)
                    constraint.isActive = true
                }
                self.setNeedsLayout()
                self.setNeedsUpdateConstraints()
            } else {
                constraints.first?.isActive = false
            }
        }
    }

}

并且子视图的所有约束优先级必须小于1000(最大999)

使用:

childView.isGone = true

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-10
    • 2018-04-26
    • 2012-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-04
    • 1970-01-01
    相关资源
    最近更新 更多