Increasing height of UIView and changing backgroun

2019-08-30 09:35发布

问题:

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.

回答1:

check whether u have Autolayout enabled if so remove the spacing .and incerase the height of subview by view.frame = CGrectMake(x,y,yourwidth,yourincreasedheight)



回答2:

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]];


回答3:

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);


回答4:

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