Ian Warburton
Ian Warburton

Reputation: 15666

Why doesn't view change when I change bounds?

If I change a UIView's bounds from...

v2.bounds = CGRect(0, 0, 70, 70)

to...

v2.bounds = CGRect(-2000, 0, 70, 70)

... nothing happens - the dimensions stay the same upon rendering. Why is this?

Upvotes: 0

Views: 36

Answers (2)

allenh
allenh

Reputation: 6622

To help understand what bounds does, run this sample code in a view controller's viewDidLoad method:

let newView = UIView(frame: CGRect(x: 50, y: 100, width: 30, height: 30))
newView.backgroundColor = UIColor.blue

let secondView = UIView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
secondView.backgroundColor = UIColor.red

newView.addSubview(secondView)


view.addSubview(newView)

DispatchQueue.main.asyncAfter(deadline: .now() + 1) {

    newView.bounds = CGRect(x: 10, y: 0, width: 30, height: 30)
}

Here we're moving the bounds to the right by 10 points, so you'll see the "second view" (which is red) move to the left by 10 points.

Changing the origin of the bounds changes the coordinate system of the view, which affects the location of all of it's subviews. It doesn't affect its origin with respect to its super view, however. For that, you should change the origin of the frame.

Upvotes: 1

Vicente Garcia
Vicente Garcia

Reputation: 6360

Bounds only takes into account width and height, you are only changing the origin in your example, only changing x to be precise. To accomplish this use frame property:

v2.frame = CGRect(-2000, 0, 70, 70)

Upvotes: 0

Related Questions