首页 > 解决方案 > UiScrollview 内容在后台重复

问题描述

我正在尝试创建一个简单的天气应用程序,我需要一个简单的图像来滚动,UIScrollView但我注意到,当我将背景颜色设置为清晰或透明时,图像在背景中是静态的,而“副本”是滚动的并且UIScrollView由于一张图片值一千字,这里有一个默认没有图片的证明。

这是 Xcode 中的层次结构。它只是一个带有图像的滚动视图。

XCode 层次结构图

这就是模拟器。我向左滚动了一下,你可以看到它的副本在背景中是静态的。

模拟器图片

如果我为滚动视图设置背景颜色,它工作正常。图像可以滚动,副本消失了,但我需要它是透明的。如果值得一提,我正在虚拟机中运行它。

这是将 XIB 文件添加到视图的代码。

[[NSBundle mainBundle] loadNibNamed:@"WeatherForecastSlideView" owner:self options:nil];
[self addSubview:self.contentView];

我希望这个问题很清楚,对错别字/错误感到抱歉。

标签: objective-cxcodeuiscrollview

解决方案


事实证明,构造函数方法有一个错字,init方法正在调用instatiante nib文件并将nib层次结构视图添加为类的子视图,问题是从代码中调用init方法来实例化类,然后从框架调用 initWithFrame 以创建和放置视图。

-(id) init{
    self = [super init];
    if (self) {
        [self internalInit];
    }
}

-(id) initWithCoder:(NSCoder *)aDecoder{
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self internalInit];
    }
    return self;
}

-(id) initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self internalInit];
    }
    return self;
}

所以基本上改变是从 init 方法中删除对内部 init 的调用

-(id) init{
    self = [super init];
    return self;
}

作为参考,这是 internalInit 方法

-(void)internalInit{
    [[NSBundle mainBundle] loadNibNamed:@"WeatherForecastSlideView" owner:self options:nil];
    [self addSubview:self.contentView];
    self.scrollView.delegate = self;
    self.translatesAutoresizingMaskIntoConstraints = NO;
    NSLayoutConstraint* height = [self.heightAnchor constraintEqualToConstant:self.contentView.bounds.size.height];
    height.active = YES;
    height.priority = UILayoutPriorityDefaultHigh;
    NSLayoutConstraint* width = [self.widthAnchor constraintEqualToConstant:self.contentView.bounds.size.width];
    width.active = YES;
    width.priority = UILayoutPriorityDefaultHigh;
}

如果多次调用该方法,则会向当前视图添加更多子视图,这会导致问题


推荐阅读