OGeek|极客世界-中国程序员成长平台

标题: ios - 无法更改自定义 View 的框架大小 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 16:28
标题: ios - 无法更改自定义 View 的框架大小

我有一个自定义的 uiview。我使用 xib 来布局 subview 并添加约束来自动布局它们。吹是在IB。 enter image description here

enter image description here

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

- (id)initWithFrameCGRect)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)

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

添加: 这是自定义 View 中 UI 内容的所有约束。 enter image description here

enter image description here

enter image description here



Best Answer-推荐答案


混合使用 Autolayout 和 setFrame 通常是一个坏主意,这会在您尝试调试时导致很多麻烦。您是否使用“捕获 View 层次结构”查看了自动生成的约束?

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

  1. 不要将多个 View 直接附加到 ScrollView 。你想要一个 附加到 ScrollView 的 View ,以及其他所有内容的 subview 那。我通常称之为内容 View 。
  2. 确保您的内容 View 正确附加到您的 ScrollView 之前 添加其他内容(无错误/警告)。
  3. 插入带有约束的 Assets View 。 0 左右,0 到 最后一个 View 。不管你是使用 constraintWithItem 还是 constraintsWithVisualFormat。
  4. 将内容 View 的底部绑定(bind)到最后插入的 subview ,使其具有 定义高度,删除或取消任何其他高度限制的优先级。

关于ios - 无法更改自定义 View 的框架大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32901182/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4