简体   繁体   中英

Increasing height of UIView and changing background colour - can't make it work

I've drawn a UIView (scrollInner) in Interface Builder and I now want to increase its height programmatically and also change its background colour.

The UIView is inside a UIScrollView , and the scrolling all works fine. Basically, what I'm doing is trying to increase the inner UIView so it matches the contentSize of the UIScrollView .

Here's what I've got so far in my viewDidAppear method:

CGRect scrollInnerRect = self.scrollInner.frame;
scrollInnerRect.size.height = 1000;
self.scrollInner.frame = scrollInnerRect;
[self.scrollInner setBackgroundColor:[UIColor redColor]];

The background colour of the UIView changes to red as expected, but the height of the 'UIView' remains the same size as it was set in Interface Builder.

However, if I do this:

NSLog(@"My uiview's frame is: %@", NSStringFromCGRect(scrollInner.frame));

I get this in the log:

My uiview's frame is: {{0, 150}, {320, 1000}}

...which suggests that the UIView 's height has been increased.

But that's not how it appears in the simulator. In other words, on screen the UIView is coloured red, but DOES NOT have the new height of 1000px - it's still way shorter.

Any ideas where I might be going wrong?

Thx.

检查是否已启用自动布局,如果删除间距并通过view.frame = CGrectMake(x,y,yourwidth,yourincreasedheight)确定子视图的高度

You can add connection in interface builder from your UIView to your class extension to create properties. And after that you can make the changes in code like that.

self.myView.frame = self.scrollInner.contentSize.

And you can change your UIView colour like that:

[self.myView setBackgroundColor:[UIColor redColor]];

Disable the 'use Autolayout' property in the identity inspector check your outlets properly in the xib file after that write this code :

CGRect scrollInnerRect = self.scrollInner.frame;

scrollInnerRect.size.height = CGrectMake(x,y,320,1000);

You might have fixed this issue. This may help others.

We can create and hold the reference of NSLayoutConstraint for the view height.

@property (weak, nonatomic) IBOutlet NSLayoutConstraint * scrollInnerHeightConstraint;

And we can use this height constraint to update the view height wherever we need

scrollInnerHeightConstraint.constant = 1000;//1000 is your height
scrollInnerHeightConstraint.priority = 1000;//1000 is High priority

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