PaddedView
是一个 UIView
子类,当它的内容的高度或宽度为零时,将其 layoutMargins
设置为 UIEdgeInsetsZero
。
这使得创建需要显示填充但是内容为 nil 时填充需要消失的视图变得容易。
//setup your view:
let redLabel = UILabel()
redLabel.text = "I'm padded. Tap me"
redLabel.backgroundColor = UIColor.redColor()
//Add it as the content of a PaddedView, include the padding:
let redLabelPadded = PaddedView(content: redLabel, bottomPadding: 10)
//add the padded view to the superview:
viewsDict["redLabel"] = redLabelPadded
view.addSubview(redLabelPadded)
//Set up your other constraints:
let constraints = [
"H:|-[imageView]-|",
"H:|-[redLabel]-|",
"H:|-[blueView]-|",
"V:|-30-[imageView][redLabel][blueView(20)]"
].flatMap {
NSLayoutConstraint.constraintsWithVisualFormat($0, options: [], metrics: nil, views: viewsDict)
}
NSLayoutConstraint.activateConstraints(constraints)
//When you set the content of the paddedview to nil, its size will
//become zero, and its padding will disappear:
func tapped() {
redLabel.text = nil
}