【发布时间】:2016-05-07 23:07:08
【问题描述】:
在viewDidLoad 中,我实例化了一个UIView 并向该UIView 添加了一个渐变层。
这在 iPhone 上运行良好,但在 iPad 上,UIView 不会伸展以填满整个屏幕。请注意以下 iPad sim 屏幕截图。
我尝试通过编程方式和使用 XCode 添加约束。
似乎一旦我添加了 CAGradientLayer,UIView 不符合我设置的约束,无论是通过编程还是使用 XCode 工具。
示例代码:
gradientLayer = CAGradientLayer()
gradientLayer.frame = self.view.bounds
gradientLayer.locations = [0.5, 1.0]
gradient_View.backgroundColor = UIColor.blueColor()
let color1 = self.opus_Page_Background_Color.CGColor as CGColorRef
let color4 = self.opus_Page_Tertiary_Color.CGColor as CGColorRef
gradientLayer.colors = [color1, color4]
self.gradient_View.frame = self.view.bounds
self.gradient_View.layer.insertSublayer(gradientLayer, atIndex: 0)
gradient_View.translatesAutoresizingMaskIntoConstraints = false
let leadingConstraint = NSLayoutConstraint(item: gradient_View, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 0)
leadingConstraint.active = true
view.addConstraint(leadingConstraint)
let trailingConstraint = NSLayoutConstraint(item: gradient_View, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 0)
trailingConstraint.active = true
view.addConstraint(trailingConstraint)
let widthConstraint = NSLayoutConstraint(item: gradient_View, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 100)
view.addConstraint(widthConstraint)
let heightConstraint = NSLayoutConstraint(item: gradient_View, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 100)
view.addConstraint(heightConstraint)
NSLayoutConstraint.activateConstraints([leadingConstraint, trailingConstraint, widthConstraint, heightConstraint])
【问题讨论】:
-
请按照@arun 删除宽度限制
-
解决方案是将代码放在
viewDidLayoutSubviews中。我保留了任意约束,因为我试图查看是否有任何约束有效,但也感谢您提供的这些提示。
标签: ios swift uiview uiviewcontroller cagradientlayer