【问题标题】:How do I Get My HeightAnchor Working Properly?如何让我的 HeightAnchor 正常工作?
【发布时间】:2018-10-07 21:14:25
【问题描述】:

在我的 MainVC 中,我试图将 UIView 限制在顶部、左侧、右侧,并且高度为 80。现在,我的视图是全屏的。我将如何修复我的代码以使其具有正确的大小?

// 变量 var topViewCons : [NSLayoutConstraint] = []

// Constants
let topGradient = RadialGradientLayer()
let topMainView = UIView()
// MainVC Top View Constraints
topMainView.translatesAutoresizingMaskIntoConstraints = false
topGradient.frame = view.bounds
topMainView.layer.addSublayer(topGradient)
self.view.addSubview(topMainView)

let topConstraint = topMainView.topAnchor.constraint(equalTo: self.view.topAnchor)
let leftConstraint = topMainView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor)
let rightConstraint = topMainView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor)
let topViewHeight = topMainView.heightAnchor.constraint(equalToConstant: 80)
NSLayoutConstraint.activate([topConstraint, leftConstraint, rightConstraint, topViewHeight])

【问题讨论】:

    标签: ios swift xcode gradient autolayout


    【解决方案1】:

    不是全屏,是渐变色

    topGradient.frame = view.bounds  // here you make it's frame to screen bounds 
    topMainView.layer.addSublayer(topGradient)
    

    所以你需要设置

    topMainView.clipsToBounds = true
    

    override func viewDidLayoutSubviews() {
      super.viewDidLayoutSubviews()
      topGradient.frame = topMainView.bounds
    }
    

    你也可以直接做到这一点而无需让

    NSLayoutConstraint.activate([
          topMainView.topAnchor.constraint(equalTo: self.view.topAnchor),
          topMainView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
          topMainView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
          topMainView.heightAnchor.constraint(equalToConstant: 80)
    ])
    

    【讨论】:

    • 谢谢!! ClipToBounds 完美运行!!我什至可以在分机中设置约束吗?那么这样我的 VC 就更干净了?
    • 是的,您可以为 UIViewController 创建一个扩展函数并传递锚点、子视图和父视图,并在其中设置所有其他内容
    • 甜蜜!这是我第一个以编程方式使用自动布局的应用程序。所以谢谢你帮助我。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-30
    • 2015-05-08
    • 2020-08-27
    • 2018-06-11
    • 2016-08-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多