【发布时间】:2019-08-19 11:39:57
【问题描述】:
我有一个基本 UIView,它有一个 visualEffectView 作为它的子视图。我将 visualEffectView 的视图 frame.height 设置为 80。当呈现给 ViewController 时,我想将其高度重置为 120。目前,当呈现时,高度最初是 120,但随后迅速回落到 80。我的框架不应该在我的 ViewController 会覆盖 UIView 中设置的框架吗?我在 ViewController 中的框架首先被调用,但后来它被 UIView 调用,导致剪辑错误。
class CardView: UIView {
let visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .light))
override init(frame: CGRect) {
super.init(frame: frame)
clipsToBounds = true
addSubview(visualEffectView)
}
override func layoutSubviews() {
super.layoutSubviews()
visualEffectView.anchor(top: topAnchor, left: leftAnchor, bottom: nil, right: rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 0, height: 80)
}
}
class ViewController: ViewController {
let cardView: CardView = {
let cv = CardView()
cv.imageView.clipsToBounds = true
cv.layer.cornerRadius = 18
return cv
}()
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let superviewFrame = view.frame.height
cardView.frame = CGRect(x: 10, y: superviewFrame / 8, width: view.frame.width - 20, height: superviewFrame - (superviewFrame / 5))
cardView.visualEffectView.anchor(top: cardView.topAnchor, left: cardView.leftAnchor, bottom: nil, right: cardView.rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 0, height: 120)
}
}
【问题讨论】:
-
尝试将
cardView.visualEffectView.translatesAutoresizingMaskIntoConstraints设置为 false,或者放弃整个框架的方法并改用约束。 -
您在问题中提到了您的约束,但您没有使用任何约束。您的代码没有使用任何应该使用的自动布局。此外,子类化
UIView可能是一个涉及的过程,我建议阅读stackoverflow.com/questions/15978370/… 您可能希望在自定义视图中使用updateConstraints生命周期方法。 -
使用锚约束时,大小甚至不调整。
-
抱歉,我还在学习行话。我认为设置框架的高度是一个约束。
-
不用担心。在定位和调整视图大小时,您希望尽量避免在视图的 frame 属性中执行此操作。让自动布局为您完成。