UIScrollView内容宽度异常求助:3张图可额外分页滚动2次
UIScrollView 分页后出现多余空白区域的解决思路
兄弟,我一眼就瞅出你代码里的问题啦——你计算contentWidth的逻辑完全跑偏了!咱们来拆解下:
你现在是在循环里把每次的newX累加起来,比如3张图的情况:
- 第1张图的
newX是scrollWidth/2 - 第2张是
scrollWidth/2 + scrollWidth - 第3张是
scrollWidth/2 + 2*scrollWidth
加起来总宽度就是(0.5 + 1.5 + 2.5)*scrollWidth = 4.5*scrollWidth,但实际上分页滚动只需要3*scrollWidth的宽度,这就导致了多余的空白和额外的分页。
核心解决思路
- 修正contentWidth的计算逻辑:直接用
scrollWidth * CGFloat(bannerImages.count),因为每一页的宽度就是scrollView的宽度,不管图片放在页面的哪个位置,contentSize的宽度只需要覆盖所有分页的总宽度。 - 调整图片的x坐标计算:保持图片在每一页居中的逻辑,但不要用这个值来累加contentWidth。
修正后的代码
func setupScrollView(){ let scrollWidth = scrollView.frame.size.width let scrollHeight = scrollView.frame.size.height scrollView.isPagingEnabled = true // 直接用分页数量乘以scrollView宽度作为总内容宽度 let contentWidth = scrollWidth * CGFloat(bannerImages.count) for x in 0..<bannerImages.count { guard let image = UIImage(named: bannerImages[x]) else { continue } // 加个安全解包更稳妥 let imageView = UIImageView(image: image) imageView.clipsToBounds = true // 计算当前页的中心x坐标,保证图片在页面居中 let pageCenterX = scrollWidth * CGFloat(x) + scrollWidth/2 imageView.frame = CGRect( x: pageCenterX - itemWidth/2, y: scrollView.frame.midY - itemWidth/2, width: itemWidth, height: itemWidth ) scrollView.addSubview(imageView) } scrollView.contentSize = CGSize(width: contentWidth, height: scrollHeight) }
额外注意事项
- 记得给
itemWidth设置合理的值,不要超过scrollWidth,否则图片会超出页面范围; - 加个
guard let解包图片,避免因为图片名错误导致的空值问题; - 循环用
0..<bannerImages.count比0...bannerImages.count-1更简洁规范。
内容的提问来源于stack exchange,提问作者Barkley
相关产品推荐
相关产品推荐

