我正在创建一个customview
,它是UIScrollView
的子类。我在UIButtons
内动态添加了UIScrollView
以及图片和动作。但是scrollview
没有按钮水平滚动。我知道在SO上多次讨论过这个话题。我尝试了在SO上发布的所有帖子,但没有得到预期的结果。关于我哪里出错的任何建议都会有所帮助。
MyCustomView.h
@interface MyCustomView : UIScrollView
@property (strong, nonatomic) IBOutlet UIScrollView *scrollView;
+ (id)customView;
@end
MyCustomView.m
@implementation MyCustomView
@synthesize scrollView;
+ (id)customView
{
MyCustomView *customView = [[[NSBundle mainBundle] loadNibNamed:@"MyCustomView" owner:nil options:nil] lastObject];
if ([customView isKindOfClass:[MyCustomView class]])
return customView;
else
return nil;
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
}
return self;
}
- (void)drawRect:(CGRect)rect
{
[self setupHorizontalScrollView];
}
- (void)setupHorizontalScrollView
{
//scrollView.delegate = self;
[self.scrollView setBackgroundColor:[UIColor blueColor]];
[scrollView setCanCancelContentTouches:YES];
scrollView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
scrollView.clipsToBounds = NO;
scrollView.scrollEnabled = YES;
//scrollView.pagingEnabled = YES;
CGFloat cx = 0;
NSArray *buttons = @[@{@"Tag":@1,@"Image":[UIImage imageNamed:@"borderImage1.png"]},
@{@"Tag":@2,@"Image":[UIImage imageNamed:@"borderImage2.png"]},
@{@"Tag":@3,@"Image":[UIImage imageNamed:@"borderImage3.png"]},
@{@"Tag":@4,@"Image":[UIImage imageNamed:@"borderImage4.png"]},
@{@"Tag":@1,@"Image":[UIImage imageNamed:@"borderImage1.png"]},
@{@"Tag":@2,@"Image":[UIImage imageNamed:@"borderImage2.png"]},
@{@"Tag":@3,@"Image":[UIImage imageNamed:@"borderImage3.png"]},
@{@"Tag":@4,@"Image":[UIImage imageNamed:@"borderImage4.png"]},
@{@"Tag":@1,@"Image":[UIImage imageNamed:@"borderImage1.png"]}
];
// CGRect frame = CGRectMake(0.0f, 0.0f, 50.0f, 30.0f);
for (NSDictionary *dict in buttons)
{
UIButton *button =[UIButton buttonWithType:UIButtonTypeRoundedRect];
CGRect rect = button.frame;
rect.size.height = 40;
rect.size.width = 40;
rect.origin.x = cx;
rect.origin.y = 0;
button.frame = rect;
button.tag = [dict[@"Tag"] integerValue];
[button setImage:dict[@"Image"]
forState:UIControlStateNormal];
// [button addTarget:self action:@selector(buttonAction:)
// forControlEvents:UIControlEventTouchUpInside];
[self.scrollView addSubview:button];
//frame.origin.x+=frame.size.width+20.0f;
cx += button.frame.size.width+5;
}
[scrollView setContentSize:CGSizeMake(cx, [scrollView bounds].size.height)];
}
@end
我经历了以下SO链接,但没有得到解决方案。
答案 0 :(得分:0)
为了能够滚动,您需要保持滚动视图的视图超出屏幕范围。因此,拖动视图并将其放大到设备边界,以便它能够保存您的子视图。
答案 1 :(得分:0)
最好使用UICollectionView来解决这类问题。它更容易实现,也可以帮助您进行所有必要的操作。
答案 2 :(得分:0)
您的MyCustomView
是UIScrollView
的子类。因此,您不需要为您的班级添加UIScrollView
财产。删除scrollView
媒体资源,并将所有self.scrollView
替换为self