无法更改自定义视图的框架尺寸

时间:2015-10-02 05:43:01

标签: ios objective-c iphone xcode6 autolayout

我有自定义uiview。我使用xib来布局子视图并添加约束来自动布局它们。在IB中打击它。 enter image description here

enter image description here

现在我有一些代码覆盖了initWithFrame:方法。 这是代码。

- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
    MyCustomView *view = [[NSBundle mainBundle] loadNibNamed:@"MyCustomView" owner:self options:nil].firstObject;
    [self addSubview:view];
}
return self;

}

而且,在其他一些来源中,我使用上面定义的initWithFrame:方法创建它并将其添加到UIScrollView。我使用约束来让scrollview的框架适合屏幕尺寸。代码在这里。

CGRect contentRect = CGRectZero;
for (int index = 0;index < self.valueData.count;index ++) {
    MyCustomView *cellView = [[MyCustomView alloc] initWithFrame:CGRectMake(0, CUSTOM_VIEW_HEIGHT * index, SCREEN_WIDTH, CUSTOM_VIEW_HEIGHT)];
    [self.scrollView addSubview:cellView];
    contentRect = CGRectUnion(contentRect, cellView.frame);
}
self.scrollView.contentSize = contentRect.size;

我在iPhone 5s模拟器中看到了什么:

enter image description here

但是在iPhone 6模拟器中:

enter image description here

虽然我将帧的宽度设置为SCREEN_WIDTH,但它们没有占据整个屏幕的宽度,这是定义的:

#define SCREEN_WIDTH ([UIScreen mainScreen].bounds.size.width)

如何设置这些自定义视图的宽度以适应多个设备中的屏幕宽度?

已添加: 以下是自定义视图中UI内容的所有约束。 enter image description here

enter image description here

enter image description here

3 个答案:

答案 0 :(得分:2)

混合使用Autolayout和setFrame通常是一个坏主意,当您尝试调试时会导致很多痛苦。你有没看过自动生成的约束呢?#34; Capture View Hierarchy&#34;?

您真正想要做的不是依赖于生成的约束(特别是因为在显示之前您不能依赖视图/窗口大小)。实际上,您需要做一些非常重要的事情:

  1. 不要将多个视图直接附加到滚动视图。你想要一个 视图附加到scrollview,以及其他所有内容作为子视图 那。我通常将其称为内容视图。
  2. 确保您的内容视图之前已正确附加到您的滚动视图 添加其他内容(无错误/警告)。
  3. 使用约束插入资产视图。 0到左右,0到 最后一个观点。如果你我们使用constraintWithItem或者,那不重要 constraintsWithVisualFormat。
  4. 将内容视图的底部绑定到最后插入的子视图,使其具有 定义高度,删除或取消任何其他高度限制的优先顺序。

答案 1 :(得分:0)

处设置断点
self.scrollView.contentSize = contentRect.size;

你会看到尺寸错误。

当您在xib中添加约束时,一旦调用了addSubView,它就会覆盖[super initWithFrame:]。这就是屏​​幕尺寸不起作用的原因。

您的约束看起来正确,请尝试将scrollView的contentSize设置为屏幕大小。

答案 2 :(得分:0)

添加以下方法并在添加子视图后调用它。

-(void)addBasicConstraintsOnSubView:(UIView *)subView onSuperView:(UIView *)superView
{
    [subView setTranslatesAutoresizingMaskIntoConstraints:NO];
    [superView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"V:|-%f-[subView]-0-|",subView.frame.origin.y] options: NSLayoutFormatAlignmentMask metrics:nil views:NSDictionaryOfVariableBindings(subView)]];
    [superView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"|-%f-[subView]-%f-|",subView.frame.origin.x,subView.frame.origin.x] options: NSLayoutFormatAlignmentMask metrics:nil views:NSDictionaryOfVariableBindings(subView)]];
}
相关问题