我这里有一个自定义的UIView
子类(这里是self
),它在故事板中使用了Autolayout和Size类(wAny hAny)。
此外,其中UIScrollView
和UIImageViews
中的UIScrollView
作为其分页内容。
为了获得self
的正确宽度(320 pt但不是默认宽度600或故事板中的568),我必须在UIImageView
中设置layoutSubviews
的帧,但它会导致无限循环。
另一方面,如果我在awakeFromNib
中添加imageViews,则会得到self
的错误宽度,即584(600-16)。
我应该在哪里添加子视图(6个imageViews)到scrollView以避免无限循环?
#define Self_Width CGRectGetWidth(self.bounds)
#define Self_Height CGRectGetHeight(self.bounds)
@interface YSAdScrollView ()<UIScrollViewDelegate>
@property(nonatomic) NSArray *coverAdImages;
@property(nonatomic) UIScrollView *ysCoverAdScrollView;
@end
@implementation YSAdScrollView
-(void)layoutSubviews{
[super layoutSubviews];
[self addSubview:self.ysCoverAdScrollView];
self.ysCoverAdScrollView.contentSize = CGSizeMake(Self_Width * self.coverAdImages.count , Self_Height);
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[ysCoverAdScrollView]-0-|" options:0 metrics:nil views:self.viewsDictionary]];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[ysCoverAdScrollView(106)]->=0-|" options:0 metrics:nil views:self.viewsDictionary]];
[self.coverAdImages enumerateObjectsUsingBlock:^(NSString *imageName, NSUInteger idx, BOOL *stop) {
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, idx * Self_Width, Self_Height)];
imageView.contentMode = UIViewContentModeScaleAspectFit;
imageView.translatesAutoresizingMaskIntoConstraints = YES;
imageView.image = [UIImage imageNamed:imageName];
imageView.layer.borderWidth =1 ;
NSLog(@"imageView[%d] = %@" , (int)idx , NSStringFromCGRect(imageView.frame));
[self.ysCoverAdScrollView addSubview:imageView];
}];
}
-(UIScrollView *)ysCoverAdScrollView{
if (!_ysCoverAdScrollView) {
self.ysCoverAdScrollView = [[UIScrollView alloc]
initWithFrame:CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height)];
self.ysCoverAdScrollView.translatesAutoresizingMaskIntoConstraints = NO;
}
return _ysCoverAdScrollView;
}
-(NSArray *)coverAdImages{
if (!_coverAdImages) {
_coverAdImages = [NSArray arrayWithObjects:@"coverAd4.jpg",@"coverAd1.jpg",@"coverAd2.jpg",@"coverAd3.jpg",@"coverAd4.jpg",@"coverAd1.jpg", nil];
}
return _coverAdImages;
}