我有一個視圖,說一個紅色的矩形,我有它的一個子視圖,一個綠色的矩形,全部以編程方式添加。我可以使子視圖在其大小上填充視圖嗎?
現在,我怎樣才能使一個綠色的矩形在寬度和高度上填滿整個紅色矩形而不會獲得當前屏幕的大小,這樣當紅色矩形在屏幕旋轉時調整大小,綠色矩形也會自動調整大小?
我有一個視圖,說一個紅色的矩形,我有它的一個子視圖,一個綠色的矩形,全部以編程方式添加。我可以使子視圖在其大小上填充視圖嗎?
現在,我怎樣才能使一個綠色的矩形在寬度和高度上填滿整個紅色矩形而不會獲得當前屏幕的大小,這樣當紅色矩形在屏幕旋轉時調整大小,綠色矩形也會自動調整大小?
您可以覆蓋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