自定义UIView旋转时调整大小

时间:2013-08-24 11:04:14

标签: ios

我知道有几个类似的问题,但我仍然找不到合适的解决方案。 我刚刚创建了一个带有自定义视图的测试项目:

@interface CustomView : UIView

//..

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setBackgroundColor:[UIColor redColor]];

    }
    return self;
}

和View Controller:

- (void)viewDidLoad
{
    [super viewDidLoad];

    CustomView *cv = [(CustomView *) [CustomView alloc] initWithFrame:self.view.frame];
    [self.view addSubview: cv];
}

在横向模式中,我们可以看到:

enter image description here

如何解决? 我知道layoutSubviews,但1.在旋转时没有调用它; 2.我如何在此处调整视图大小?

1 个答案:

答案 0 :(得分:2)

尝试设置autoresizingMask。

CustomView *cv = [(CustomView *) [CustomView alloc] initWithFrame:self.view.frame];
cv.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleBottomMargin;
[self.view addSubview: cv];

您还可以查看autolayout

https://developer.apple.com/library/ios/recipes/xcode_help-interface_builder/articles/UnderstandingAutolayout.html

此致