How can I set the size of a UIView init with storyboard?

∥☆過路亽.° 提交于 2019-12-07 13:51:04

问题


I am currently using iOS 6.0.

I have a custom UIView that needs to have a certain size. If I programmatically init the view and add it it's fine. However, I can't find a place where I can set the size of the view in the storyboard.

Setting its size in the storyboard doesn't work because the storyboard thinks it's empty and set it's size to zero. Setting its size in viewDidLoad or viewDidAppear doesn't work because later on the size will be overwritten by _applyISEngineLayoutValue.


回答1:


You can do that in your Interface Builder. Open the storyboard where you have your view and open the utilities menu:

Then you can select a button that looks like a ruler on the top of the utilities menu:

In that menu you can set the size of your view and how you want it to expand.

Also, please make sure you setted your Class' view in the class inspector:

Image token from this site.

Finally, make sure you override the initWithFrame and initWithCoder methods:

- (id)initWithFrame:(CGRect)frame {
    return [super initWithFrame:frame];
}

//Needs to be overrided when you set your size in interface builder
- (id)initWithCoder:(NSCoder *)aDecoder {
    return [self initWithFrame:[self frame]];
}



回答2:


I am facing the same problem, and I think the short answer is: you can't rely on the frame or bounds in the view's init method when using storyboards.

When your view is initialized by the segue, it will call the initWithCoder: method rather than other init methods, since it is deserializing your view object from the .xib file. Before storyboards, the frame and bounds would be set by the time the initWithCoder: was called, but that appears to no longer be the case with storyboards -- the iOS code sets those values later.

I've used a couple workarounds, depending on the situation:

  1. If I know the size of the view in advance (for example a specialty view that only supports one size) I set my own frame in the initWithCoder: method.

  2. If I don't know the size of the view, I defer initialization of size-specific things until my view's layoutSubviews method is called.

  3. If it's more convenient, I sometimes just explicitly do the size-specific initialization in my view's ViewController. (Not pretty, but sometimes quick-and-easy. I'm not proud.)




回答3:


I have the same problem as you, and when I select the view and switch to the attributes inspector , setting "Simulated Metrics" as follows, I can resize the view in the Size inspector.

Make sure that Size is set to either "Freeform" or "None"



来源:https://stackoverflow.com/questions/12758782/how-can-i-set-the-size-of-a-uiview-init-with-storyboard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!