我在学习自动布局方面遇到了很大问题,尤其是在集成xib和uiscrollviews时。为了简化我的问题,我开始了一个新项目,其中一个视图与故事板相关联。然后,我将UIView(Diptic
)子类化,并为其创建了一个xib文件。我的故事板没有使用自动布局,但我的Diptic xib是。现在我想要一个横向scrollView,其上有几个Diptic实例。但我只是得到第一个diptic实例出现,因为框架没有正确初始化。
在我的ViewController.m的viewDidLoad中:
self.scrollView.contentSize = CGSizeMake((self.view.frame.size.width+10)*5, self.view.frame.size.height);
for (int i = 0; i < 5; i++){
int x = i*(self.view.frame.size.width+10);
Diptic *diptic = [[Diptic alloc] initWithFrame:CGRectMake(x, 50, self.view.frame.size.width, self.view.frame.size.height-100)];
[self.scrollView addSubview:diptic];
[array addObject:diptic];
UIView *greenBox = [[UIView alloc] initWithFrame:CGRectMake(x, 5, 40, 40)];
greenBox.backgroundColor = [UIColor greenColor];
[self.scrollView addSubview:greenBox];
}
Diptic.m
#import "Diptic.h"
@implementation Diptic
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
NSArray* views = [[NSBundle mainBundle] loadNibNamed:@"Diptic" owner:nil options:nil];
self = [views objectAtIndex:0];
self.label.text = @"WOOT";
self.backgroundColor = [UIColor redColor];
}
return self;
}
@end
如果我在将其添加到视图后设置框架似乎有效,但为什么我不能用initWithFrame
设置框架?
答案 0 :(得分:0)
此处的问题是您将框架分配给通过调用[super initWithFrame:frame]
创建的视图。在- (id)initWithFrame:(CGRect)frame
中加载NIB时,self
将替换为[views objectAtIndex:0]
中的视图,并且永远不会设置此视图的帧。相反,取消对super
的调用并改为从NIB加载视图:
#import "Diptic.h"
@implementation Diptic
- (id)initWithFrame:(CGRect)frame
{
NSArray *views = [[NSBundle mainBundle] loadNibNamed:@"Diptic" owner:nil options:nil];
self = [views objectAtIndex:0];
if (self) {
self.frame = frame;
self.label.text = @"WOOT";
self.backgroundColor = [UIColor redColor];
}
return self;
}
@end
答案 1 :(得分:0)
从storyboard或xib初始化视图/控制器时,init方法是
- (id)initWithCoder:(NSCoder *)decoder
尝试在此方法中做其他事情