Paul
Paul

Reputation: 6176

UIScrollview does not react to any touch?

I am trying to do a simple scroll, but the views do not move after a touch, I am not sure why, the scrollview should handle the gesture, but something might be missing. Would someone know where?

Here is the code : I create a small horizontal scroll view, with some views inside. The views appear well, I am testing it on a device for the touch :

- (void)viewDidLoad {
    [super viewDidLoad];
    //horizontal scroll view
    HorizScroll *ho = [[HorizScroll alloc] initWithFrame:CGRectMake(0, 0, 500, 100)];
    for ( int i=0; i<3; i++){
        MyView* mv = [[MyView alloc] init];
        [ho addSubview:mv];
    }
    //ho.zoomScale = 0.3f;
    [self.view addSubview:ho];
}





@implementation HorizScroll
- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
    }
    return self;
}

-(void)addSubview:(UIView *)view{
    [super addSubview:view];
    NSUInteger numSubviews = self.subviews.count;
    [view setFrame:CGRectMake(CGRectGetWidth(view.bounds)*(numSubviews),
                             0,
                             CGRectGetWidth(view.bounds),
                             CGRectGetHeight(view.bounds) )];
    [self setContentSize:CGSizeMake(CGRectGetWidth(view.bounds)*(numSubviews),
                                   CGRectGetHeight(view.bounds) )];
}









@implementation MyView
-(int)getRandomNumberBetween:(int)from to:(int)pto {
    return (int)(from + arc4random() % (pto-from+1));
}
-(instancetype)init{
    if ( self = [super init] ){
        CGFloat red = [self getRandomNumberBetween:1 to:255];
        self.backgroundColor = [UIColor colorWithRed:red/256.0
                                               green:[self getRandomNumberBetween:1 to:255]/256.0
                                                blue:[self getRandomNumberBetween:1 to:255]/256.0
                                               alpha:1.0];
    }
    return self;
}

-(instancetype)initWithFrame:(CGRect)frame{
    if ( self = [super initWithFrame:frame] ){
        self.frame = CGRectMake(counterX, 0, 100, 100);
        counterX += 50;
    }
    return self;
}

Upvotes: 0

Views: 82

Answers (1)

gabbler
gabbler

Reputation: 13766

You need to set contentSize of scrollview to be larger than its frame size. so add this line after [self.view addSubview:ho].

ho.contentSize = CGSizeMake(501.f, 100.f);

or before [self.view addSubview:ho] and comment out the line:

[self setContentSize:CGSizeMake(CGRectGetWidth(view.bounds)*(numSubviews),
                                CGRectGetHeight(view.bounds))];

which is not necessary since you can set it after all subviews are added.

Upvotes: 1

Related Questions