我正在尝试以编程方式将自定义视图添加到现有的 UIScrollView。我上网并找到了可能的解决方案,但解决方案搞砸了现有的自动布局。我需要在自定义视图(即滚动视图)的超级视图和自定义视图之间添加一个垂直空间。因此,每当用户从大屏幕(iPhone5)切换到小屏幕(比如 iPhone4s)或反之亦然,自定义视图都会在屏幕上进行相应调整。
-(void) createEventsOnScroll
{
[imageScroller setContentSize:CGSizeMake(self.imageArray.count*imageScroller.frame.size.width, imageScroller.frame.size.height)];
[imageScroller setContentOffset:CGPointMake(imageScroller.frame.size.width*self.selectedEventIndex,0)];
imageScroller.showsHorizontalScrollIndicator = NO;
for (int i = 0; i<self.imageArray.count; i++)
{
EventCustomView *event = [[EventCustomView alloc]initWithFrame:CGRectMake(i*320+5, 3, 310, 435)];
ChildImage *child = [self.imageArray objectAtIndex:i];
NSData *data = [NSData dataWithContentsOfFile:child.imageURL];
event.eventImage.image = [UIImage imageWithData:data];
[event.eventImage setContentMode:UIViewContentModeScaleAspectFit];
event.noteView.delegate = self;
[imageScroller addSubview:event];
event.translatesAutoresizingMaskIntoConstraints = NO;
imageScroller.translatesAutoresizingMaskIntoConstraints = NO;
NSMutableArray *constraints = [[NSMutableArray alloc]init];
[constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"|[event]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(event)]];
[constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[event]-5-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(event)]];
}
imageScroller.bounces = NO;
imageScroller.delegate = self;
[imageScroller setClipsToBounds:NO];
imageScroller.scrollEnabled = YES;
imageScroller.pagingEnabled = YES;
}
提前致谢。