【问题标题】:how to set height constraint in IBDesignable file?如何在 IBDesignable 文件中设置高度约束?
【发布时间】:2018-10-16 02:29:10
【问题描述】:

我需要制作一个 IBDesignable 来制作一个自定义导航栏文件,该文件将根据 iPhone 类型调整视图的高度。如果 iPhone 像 iPhone X,XR 一样有一流,那么高度限制为 88,否则对于没有一流的 iPhone 8,高度限制为 64。

我需要设置高度约束,而不是层高。这是我使用的代码,但它无法更新高度约束

import UIKit

@IBDesignable
class CustomParentNavigationBarView: UIView {

    override func awakeFromNib() {
        super.awakeFromNib()
        self.setHeight()
    }


    func setHeight() {
        let deviceHasTopNotch = checkHasTopNotchOrNot()
        var heightConstraint = NSLayoutConstraint()

        if deviceHasTopNotch {

            heightConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: 88)

        } else {

            heightConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: 64)

        }

        heightConstraint.isActive = true
        self.addConstraint(heightConstraint)


    }

    func checkHasTopNotchOrNot() -> Bool {
        if #available(iOS 11.0, tvOS 11.0, *) {
            // with notch: 44.0 on iPhone X, XS, XS Max, XR.
            // without notch: 20.0 on iPhone 8 on iOS 12+.
            return UIApplication.shared.delegate?.window??.safeAreaInsets.top ?? 0 > 20
        }
        return false
    }





}

结果应该是这样的(红色视图),红色视图的高度应该根据 iPhone 类型而变化,88 或 64

对于初始值,我像这样在故事板中设置视图的自动布局

【问题讨论】:

  • translatesAutoresizingMaskIntoConstraints = false?
  • 我没有那个代码
  • 尝试添加。
  • 我必须把 translatesAutoresizingMaskIntoConstraints = false 放在哪里?在 awakefromNib 中?
  • 如果您使用 storboard,它应该可以作为一个选项使用。

标签: ios swift uiview autolayout


【解决方案1】:

我可以看到两个问题。

  1. 您没有激活约束。添加这一行 heightConstraint.isActive = true

  2. 您多次调用 SetHeight。每次都会添加一个约束。这将导致约束冲突和不良行为。相反,只需创建一次约束并将其存储为成员。

【讨论】:

  • 我已经编辑了我上面的代码,我添加了 heightConstraint.isActive = true 并且只实现了一次 setHeight,但是高度还是一样的,我编辑代码对吗?
  • 你确定调用了 awakeFromNib 和 setHeight 吗?
  • 是的,先生,上面的代码与我的 IBDesignable 文件完全相同。然后我在情节提要的所需视图中分配 CustomParentNavigationBarView
  • 您是否在情节提要中为此视图使用了约束?
  • 如果不是,您需要为前导、尾随和顶部添加约束。以编程方式或在情节提要中。如果您以编程方式执行此操作,您还需要 translatesAutoresizingMaskIntoConstraints = false
猜你喜欢
  • 2019-02-19
  • 2015-08-30
  • 1970-01-01
  • 1970-01-01
  • 2021-08-12
  • 1970-01-01
  • 1970-01-01
  • 2022-01-21
  • 1970-01-01
相关资源
最近更新 更多