ios - UIScrollview 对任何触摸都没有反应?

标签 ios objective-c uiscrollview

我正在尝试做一个简单的滚动,但触摸后 View 不会移动,我不确定为什么, ScrollView 应该处理手势,但可能缺少某些东西。有人知道在哪里吗?

这是代码:我创建了一个小的水平 ScrollView ,里面有一些 View 。 View 看起来不错,我正在触摸设备上测试它:

- (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;
}

最佳答案

您需要将scrollview的contentSize设置为大于其框架大小。因此,请在 [self.view addSubview:ho] 之后添加此行。

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

或在[self.view addSubview:ho]之前并注释掉该行:

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

这不是必需的,因为您可以在添加所有 subview 后设置它。

关于ios - UIScrollview 对任何触摸都没有反应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27359590/

相关文章:

iphone - 如何让scrollViewDidScrollToTop 在 UITableView 中工作?

ios - 替换 iOS 15 中已弃用的 `SecTrustGetCertificateAtIndex`?

ios - 创建一个NSString变量的C宏,变量名作为字符串的内容

ios - 如何使用 UIScrollView 实现 UIPageViewController?

iphone - 神秘的UITableView卡住问题

iOS/Swift - 向下/向上滚动时隐藏/显示 UITabBarController

ios - 目标 - C : UITableView Content Changing on Scroll

ios - (Swift 3) - 如何在自定义 UIView 中包含动画

iOS Game Center GameKit 程序化邀请对接会

ios - API 1.1 版的 Twitter 授权