基于屏幕高度子类化 NSLayoutConstraint 常量 [英] Subclassing NSLayoutConstraint constant based on screen height

查看:65
本文介绍了基于屏幕高度子类化 NSLayoutConstraint 常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有标签栏的项目,每个标签都有一个自定义导航栏.每个导航栏 UIViews 都在故事板中设置了一个高度约束常量.

I have a project with a Tab Bar, and a custom Navigation bar for each of the tabs. Each of the Navigation bar UIViews have a height constraint constant set in the storyboard.

我想将此 NSLayoutConstraint 子类化(用于导航高度),以便它更改 iPhone X 的高度.iPhone X 上的导航栏需要更高,并且由于我没有使用out of框"对象,我的约束需要手动设置.

I would like to subclass this NSLayoutConstraint (for the Nav height), so that it changes the height for iPhone X. The Navigation bar needs to be much taller on an iPhone X, and since I'm not using "out of the box" objects, my constraints need to be manually set.

本质上,我想在子类中做类似下面的事情,这样我就不必重复一堆代码并制作不必要的插座:

Essentially, I want to do something like the following in the subclass, so I don't have to repeat a bunch of code and make unnecessary outlets:

override func viewWillLayoutSubviews() {
    navBarHeightConstraint.constant = navBarHeightConstraintConstant()
}

func navBarHeightConstraintConstant() -> CGFloat {
    switch(UIScreen.main.bounds.height) {
    case 812: // iPhone X
        return 90
    default: // all others
        return 64
    }
}

我已经创建了子类,但不知道使用什么方法来执行上述代码.

I have created the subclass, but don't know what methods to use to perform the above code.

class NavHeightFixiPhoneXConstraint: NSLayoutConstraint {

    // Nothing... yet!

}

如何子类化 NSLayoutConstraint 以便它仅显示 iPhone X 的特定值?

推荐答案

您可以覆盖常量变量:

final class NavHeightFixiPhoneXConstraint: NSLayoutConstraint {

    override var constant: CGFloat {
        set {
            super.constant = newValue
        }
        get {
           return navBarHeightConstant()
        }
    }

    private func navBarHeightConstant() -> CGFloat {
        switch (UIScreen.main.bounds.height) {
         case 812:
            return 90
         default: 
             return 64
        }
    }
}

这篇关于基于屏幕高度子类化 NSLayoutConstraint 常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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