当我使用自动布局时,我应该在自定义UIView子类中将子视图添加到scrollview中

时间:2015-05-19 03:50:04

标签: ios objective-c uiview uiscrollview autolayout

我这里有一个自定义的UIView子类(这里是self),它在故事板中使用了Autolayout和Size类(wAny hAny)。

此外,其中UIScrollViewUIImageViews中的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;
}

0 个答案:

没有答案