简体   繁体   中英

Resize superview after changing height of subview - WITHOUT AUTO LAYOUT

Google always gives results for Auto layout when I ask this.
I have a custom view which has few subviews. One of the subview further has 2 subviews.

Superview  
  - Subview 1  
  - Subview 2  
     - Subview 21  
     - Subview 22   
  - Subview 3  

At some button action I am hiding one of the inner subviews (Subview 22). And after that I am updating the height of outer subview (Subview 2).

subheader.frame = CGRect(x: subheader.frame.origin.x, y: subheader.frame.origin.y, width: subheader.frame.size.width, height: 0)
subheader.isHidden = true
viewTop.frame = CGRect(x: viewTop.frame.origin.x, y: viewTop.frame.origin.y, width: viewTop.frame.size.width, height: 60)  
self.layoutSubviews()

subheader is a subview of viewTop and viewTop is subview of parent view.
The issue is that the height of viewTop is not changing.
Note : viewTop has a gradient background :

viewTop.setViewGradientBackground(UIColor(red: 228.0 / 255.0, green: 221.0 / 255.0, blue: 135.0 / 255.0, alpha: 1.0), backgroundColorBottom: UIColor(red: 150.0 / 255.0, green: 129.0 / 255.0, blue: 32.0 / 255.0, alpha: 1.0))  

extension UIView
{
    func setViewGradientBackground(_ backgroundColorTop: UIColor, backgroundColorBottom: UIColor)
    {
        let btnGradient = CAGradientLayer()
        btnGradient.frame = self.bounds
        btnGradient.colors = [backgroundColorTop.cgColor as CGColor, backgroundColorBottom.cgColor as CGColor]
        self.layer.insertSublayer(btnGradient, at: 0)
    }
}

self.layoutSubviews() will not work in this case. It will work only when used auto layouts. As you are managing frames manually, you should set frames for all superviews and subviews whenever you changed frame of one view. Its a tricky thing.

Try to implement Auto layouts. Auto layouts will manage these kind of things easily.

If you aren't using NSLayoutConstraints and you haven't set up any autoresizing masks then you are responsible for updating the frames yourself. layoutSubviews is applying layout based on the constraints; it is not capable of doing much without that knowledge.

The most straightforward way I can think is just to call viewTop.superview?.frame = ... and update it yourself manually if you really don't want to go the autolayout route.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM