[英]How to properly remove an UIImageView from UIScrollView?
我正在開發一個需要使用Xcode 4.5.2在視圖中加載許多圖像的應用程序
因此,在頂部,我有一個UIView
,在此UIView
,我有UIScrollView
可以顯示許多圖像,我在分頁啟用模式下使用此UIScrollView
。 由於我要加載許多圖像,因此我知道無法一次加載。 因此,我決定根據需要添加或刪除。
當應用程序啟動時,我已經在UIScrollView
加載了三個圖像,當用戶傳遞到圖像2時,我想從UIScrollView
移除圖像0。當我嘗試移除圖像0時,我的屏幕完全白了。有趣的是,如果我不嘗試刪除圖像0,當用戶傳遞到圖像3時,我想將新圖像(圖像4)加載到UIScrollView
並刪除圖像1。到目前為止,我能夠做到這一點。 基本上,我的應用程序運行良好,但是當我想刪除第一個( 索引為0 )圖像時,屏幕上出現了完全白屏。
您知道我為什么會出現這種行為嗎? 我既沒有警告也沒有錯誤。 我怎么可能刪除所有其他圖像而不是圖像0?
謝謝。
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
static NSInteger currentPage = 0 ;
CGFloat pageWidth = self.scrollView.frame.size.width ;
float fractionalPage = self.scrollView.contentOffset.x / pageWidth ;
NSLog(@"%f",fractionalPage);
if(fractionalPage == currentPage+1)
{
NSLog(@"Swipe Left");
currentPage++;
NSLog(@"Current page :%d",currentPage);
[self setLayoutImages:kLeft] ;
}
else if(fractionalPage+1 ==currentPage)
{
NSLog(@"Swipe Right");
currentPage--;
NSLog(@"Current page :%d",currentPage);
[self setLayoutImages:kRight];
}
}
-(void)setLayoutImages:(Direction )direction
{
int currentPage = self.scrollView.contentOffset.x / scrollViewWidth ;
if(direction == kLeft)
{
self.scrollView.contentSize = CGSizeMake(((currentPage+2) * scrollViewWidth), 350.0f);
if(![self.scrollView viewWithTag:currentPage+1])
{
NSString *imageName = @"iPhone.png" ;
UIImage *image = [UIImage imageNamed:imageName];
UIImageView *imageView = [[UIImageView alloc]initWithImage:image ] ;
imageView.tag = currentPage+1 ;
CGRect frame = imageView.frame ;
frame.size.height = imageHeight;
frame.size.width = scrollViewWidth ;
frame.origin.x = (currentPage+1) * scrollViewWidth ;
frame.origin.y = 0 ;
imageView.frame = frame ;
if (currentPage>2) { //To be able to remove the first image,i need to add equal here,but i got white screen.
[[self.scrollView viewWithTag:(currentPage -2)]removeFromSuperview ] ; }
[self.scrollView addSubview:imageView ] ;
}
}
else if(direction == kRight)
{
if(![self.scrollView viewWithTag:currentPage-1] && currentPage >0)
{
NSString *imageName = @"gs.jpeg";
UIImage *image = [UIImage imageNamed:imageName];
UIImageView *imageView = [[UIImageView alloc]initWithImage:image ];
imageView.tag = currentPage-1 ;
CGRect frame = imageView.frame ;
frame.size.height = imageHeight ;
frame.size.width = scrollViewWidth ;
frame.origin.x = (currentPage-1)*scrollViewWidth ;
frame.origin.y = 0 ;
imageView.frame = frame ;
[[self.scrollView viewWithTag:currentPage+2]removeFromSuperview ] ;
[self.scrollView addSubview:imageView ];
}
}
}
您可以給三個延遲Tag
每個Tag
並通過[[view viewWithtag:tag] removeFromSuperView]
重用它,也可以嘗試由nicklockwood
制作的名為iCarousel的現成項目,這是一個很棒的項目。
它可以是horizontal
和vertical
嘗試使您的視圖以標簽1而不是0開頭,因為如果我沒有記錯的話,0是未標記視圖的默認值,這可能會導致問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.