【问题标题】:How to add a subview with constraints to make the subview with the same frame as its superview?如何添加带有约束的子视图以使子视图与其父视图具有相同的框架?
【发布时间】:2015-09-28 11:59:39
【问题描述】:

UIView内我有一个方法presentView()

public func presentView() {

    UIApplication.sharedApplication().delegate?.window??.addSubview(self)

    let blurEffect = UIBlurEffect(style: .Light)
    let blurEffectView = UIVisualEffectView(effect: blurEffect)
    blurEffectView.backgroundColor = UIColor.yellowColor()
    addSubview(blurEffectView)

    let topConstraint = NSLayoutConstraint(item: blurEffectView, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Bottom, multiplier: 1, constant: 0)
    let bottomConstraint = NSLayoutConstraint(item: blurEffectView, attribute: .Bottom, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1, constant: 0)
    let leadingConstraint = NSLayoutConstraint(item: blurEffectView, attribute: .Leading, relatedBy: .Equal, toItem: self, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 0)
    let trailingConstraint = NSLayoutConstraint(item: blurEffectView, attribute: .Trailing, relatedBy: .Equal, toItem: self, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 0)

    self.addConstraints([topConstraint, bottomConstraint, leadingConstraint, trailingConstraint])

    print("newframe: \(blurEffectView.frame)")

}

但是某事是错误的,因为这是控制台上的输出:

新帧:(0.0, 0.0, 0.0, 0.0)

结果是:

【问题讨论】:

  • 如果我没看错,self 就是UIView。然后你应该将约束添加到self 而不是blurEffectView
  • @DánielNagy 我更新了问题,你能帮我解决这个问题吗?
  • 我认为在视图没有布局之前,你不会得到它的实际框架。所以在self.addConstraints 之后你现在不会得到它。
  • 再次用新信息更新了问题。我将背景颜色设置为黄色,但根本没有我的视图。
  • This SO question 有很多关于以编程方式添加约束的好信息。

标签: ios swift uiview nslayoutconstraint


【解决方案1】:

记住:

blurEffectView.translatesAutoresizingMaskIntoConstraints = false

然后:

let topConstraint = NSLayoutConstraint(item: blurEffectView, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1, constant: 0)
let bottomConstraint = NSLayoutConstraint(item: blurEffectView, attribute: .Bottom, relatedBy: .Equal, toItem: self, attribute: .Bottom, multiplier: 1, constant: 0)
let leadingConstraint = NSLayoutConstraint(item: blurEffectView, attribute: .Leading, relatedBy: .Equal, toItem: self, attribute: .Leading, multiplier: 1, constant: 0)
let trailingConstraint = NSLayoutConstraint(item: blurEffectView, attribute: .Trailing, relatedBy: .Equal, toItem: self, attribute: .Trailing, multiplier: 1, constant: 0)

addSubview(blurEffectView)
addConstraints([topConstraint, bottomConstraint, leadingConstraint, trailingConstraint])
layoutIfNeeded()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-17
    • 2015-06-25
    • 2014-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-10
    相关资源
    最近更新 更多