简体   繁体   中英

Autoresize subviews when resizing the superview

I am not able to handle the subview resizing correctly:

Suppose I have a custom UIView class, inside it contains a UIImageView.

Initially, I set up the UIViews like the followings:

// width and height are UIImage width height
// it is possible that the UIImage width height is larger than the container

self.imageView.frame = CGRectMake(0 ,0, width, height)
self.imageView.backgroundColor = UIColor.redColor()
self.imageView.contentMode = UIViewContentMode.ScaleAspectFit
self.imageView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight,.FlexibleTopMargin, .FlexibleLeftMargin, .FlexibleRightMargin, .FlexibleBottomMargin]
addSubview(self.imageView)

self.frame = CGRectMake(0, 0, width, height)
self.backgroundColor = UIColor.greenColor()

Let's call this custom UIView as MyView.

And then when I want to place this "myView" in a ViewController. I did the followings:

myView.frame = CGRectMake(xPos, yPos, 100, 100)
myView.autoResizeSubviews = true

And I found that after I did this, I got the following results. MyView place at the correct place with correct size, but the internal UIImageView got even a smaller size.

Why that happen? And how to make all the subviews inside MyView resize correctly according to the frame of MyView?

Thanks.

Oh, I found that the autoresizing mask should be set as follows:

self.imageView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight, .FlexibleRightMargin, .FlexibleBottomMargin]

This allows the anchor to be fixed at top and left, and allow resizing on the other margins.

If you are not using Auto-layout then swap bellow lines

please make sure you are setting frame after self(UIView) allocation

self.frame = CGRectMake(0, 0, width, height)
self.imageView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight,.FlexibleTopMargin, .FlexibleLeftMargin, .FlexibleRightMargin, .FlexibleBottomMargin]
addSubview(self.imageView)

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