简体   繁体   中英

How to set UIView size based on superView

I'm looking to size a UIView relative to the superView.

The view needs to be centered to the superview, both vertically and horizontally.

I want to use originalContentView because of iAd

@IBOutlet var WhiteBar: UIView!    
WhiteBar.frame = CGRect(origin: MainView.center, size: CGSize(width: 280, height: 280))

Create a function in your viewController, which takes a view, a set height, and a set width as a parameter and adds the following NSLayoutConstraints to the view's superview. You'll have to call this function after your view is already attached to the superview or it won't work.

func center(v: UIView, width: CGFloat, height: CGFloat) {
    v.setTranslatesAutoresizingMaskIntoConstraints(false)
    v.superview?.addConstraints(
        [
            NSLayoutConstraint(
                item: v,
                attribute: .CenterX,
                relatedBy: .Equal,
                toItem: v.superview,
                attribute: .CenterX,
                multiplier: 1,
                constant: 0
            ),
            NSLayoutConstraint(
                item: v,
                attribute: .CenterY,
                relatedBy: .Equal,
                toItem: v.superview,
                attribute: .CenterY,
                multiplier: 1,
                constant: 0
            ),
            NSLayoutConstraint(
                item: v,
                attribute: .Height,
                relatedBy: .Equal,
                toItem: nil,
                attribute: .NotAnAttribute,
                multiplier: 1,
                constant: height
            ),
            NSLayoutConstraint(
                item: v,
                attribute: .Width,
                relatedBy: .Equal,
                toItem: nil,
                attribute: .NotAnAttribute,
                multiplier: 1,
                constant: width
            )
        ]
    )
}

This was my final solution

I defined the width and height then subtracted it from the superview center. And loaded it in the viewDidLayoutSubviews()

        var Width: CGFloat = 280
        var Height: CGFloat = 280
        WhiteBar.frame = CGRect(x: (self.originalContentView.center.x - (Width / 2)), y: (self.originalContentView.center.y - (Height / 2)), width: Width, height: Height)

This adjust the view based on orientation as well.

You can use Autolayout (see other answers) or go to with struts: To use relative frames, it is better to use viewWillLayoutSubviews . Hope that helps.

override func viewWillLayoutSubviews() {
        customSubView.center.x = view.center.x
    }

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