在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])
答案 0 :(得分:0)
不是全屏,渐变是
topGradient.frame = view.bounds // here you make it's frame to screen bounds
topMainView.layer.addSublayer(topGradient)
所以您需要设置
topMainView.clipsToBounds = true
OR
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
topGradient.frame = topMainView.bounds
}
此外,您也可以不使用let来直接执行
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)
])