我有一个视图,说一个红色的矩形,我有它的一个子视图,一个绿色的矩形,全部以编程方式添加。我可以使子视图在其大小上填充视图吗?
现在,我怎样才能使一个绿色的矩形在宽度和高度上填满整个红色矩形而不会获得当前屏幕的大小,这样当红色矩形在屏幕旋转时调整大小,绿色矩形也会自动调整大小?
我有一个视图,说一个红色的矩形,我有它的一个子视图,一个绿色的矩形,全部以编程方式添加。我可以使子视图在其大小上填充视图吗?
现在,我怎样才能使一个绿色的矩形在宽度和高度上填满整个红色矩形而不会获得当前屏幕的大小,这样当红色矩形在屏幕旋转时调整大小,绿色矩形也会自动调整大小?
您可以覆盖Red Rectangle的layoutSubviews()
方法。在布局中,只需将红色矩形框重新分配给绿色的矩形框。这将使框架调整大小并重新定位方向。
这只是一个供参考的示例代码。
class RedRect:UIView {
void layoutSubviews(){
greenRect.frame = bounds
}
}
您可以使用Visual Format Auto Layout
了下方self == YOUR_GREEN_RECT
guard let superview = self.superview else {
return
}
self.translatesAutoresizingMaskIntoConstraints = false
superview.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[subview]-0-|", options: .DirectionLeadingToTrailing, metrics: nil, views: ["subview": self]))
superview.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[subview]-0-|", options: .DirectionLeadingToTrailing, metrics: nil, views: ["subview": self]))
或者只是使用Autoresizingmask
self.autoresizingMask = [.flexibleWidth, .flexibleHeight]
class RedRect:UIView {
void layoutSubviews(){
greenRect.frame = bounds
}
}
应该帧=界
谢谢你的回答。我会编辑它。 但是,您应该在评论中提供,而不是作为答案本身,先生。 – Ariel
Sry,我没有足够的REPUATION来评论你的帖子 – chinnawatp
那好吧。 – Ariel
let redView = UIView(frame: CGRect(x: 100, y: 100, width: 100, height: 350))
redView.backgroundColor = UIColor.redColor()
redView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
view.addSubview(redView)
let greenView = UIView(frame: redView.bounds)
greenView.backgroundColor = UIColor.greenColor()
redView.addSubview(greenView)
greenView.autoresizingMask = redView.autoresizingMask
autoresizingMask为我做了。请注意Swift 3中的.flexibleWidth和.flexibleHeight – Serdnad
您可以使用['Auto Layout'](https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/AutolayoutPG/)。 – ozgur